xref: /btstack/src/hci.c (revision 5b7087c754e520e4200e21e12b7f0324e0c8e896)
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 ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3017     conn->num_packets_completed++;
3018     hci_stack->host_completed_packets = 1;
3019     hci_run();
3020 #endif
3021 }
3022 #endif
3023 
3024 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
3025     hci_dump_packet(packet_type, 1, packet, size);
3026     switch (packet_type) {
3027         case HCI_EVENT_PACKET:
3028             event_handler(packet, size);
3029             break;
3030         case HCI_ACL_DATA_PACKET:
3031             acl_handler(packet, size);
3032             break;
3033 #ifdef ENABLE_CLASSIC
3034         case HCI_SCO_DATA_PACKET:
3035             sco_handler(packet, size);
3036             break;
3037 #endif
3038         default:
3039             break;
3040     }
3041 }
3042 
3043 /**
3044  * @brief Add event packet handler.
3045  */
3046 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3047     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3048 }
3049 
3050 
3051 /** Register HCI packet handlers */
3052 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3053     hci_stack->acl_packet_handler = handler;
3054 }
3055 
3056 #ifdef ENABLE_CLASSIC
3057 /**
3058  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
3059  */
3060 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
3061     hci_stack->sco_packet_handler = handler;
3062 }
3063 #endif
3064 
3065 static void hci_state_reset(void){
3066     // no connections yet
3067     hci_stack->connections = NULL;
3068 
3069     // keep discoverable/connectable as this has been requested by the client(s)
3070     // hci_stack->discoverable = 0;
3071     // hci_stack->connectable = 0;
3072     // hci_stack->bondable = 1;
3073     // hci_stack->own_addr_type = 0;
3074 
3075     // buffer is free
3076     hci_stack->hci_packet_buffer_reserved = 0;
3077 
3078     // no pending cmds
3079     hci_stack->decline_reason = 0;
3080     hci_stack->new_scan_enable_value = 0xff;
3081 
3082     hci_stack->secure_connections_active = false;
3083 
3084 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3085     hci_stack->classic_read_local_oob_data = true;
3086 #endif
3087 
3088     // LE
3089 #ifdef ENABLE_BLE
3090     memset(hci_stack->le_random_address, 0, 6);
3091     hci_stack->le_random_address_set = 0;
3092 #endif
3093 #ifdef ENABLE_LE_CENTRAL
3094     hci_stack->le_scanning_active  = 0;
3095     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3096     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3097     hci_stack->le_whitelist_capacity = 0;
3098 #endif
3099 }
3100 
3101 #ifdef ENABLE_CLASSIC
3102 /**
3103  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3104  */
3105 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3106     // store and open remote device db
3107     hci_stack->link_key_db = link_key_db;
3108     if (hci_stack->link_key_db) {
3109         hci_stack->link_key_db->open();
3110     }
3111 }
3112 #endif
3113 
3114 void hci_init(const hci_transport_t *transport, const void *config){
3115 
3116 #ifdef HAVE_MALLOC
3117     if (!hci_stack) {
3118         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3119     }
3120 #else
3121     hci_stack = &hci_stack_static;
3122 #endif
3123     memset(hci_stack, 0, sizeof(hci_stack_t));
3124 
3125     // reference to use transport layer implementation
3126     hci_stack->hci_transport = transport;
3127 
3128     // reference to used config
3129     hci_stack->config = config;
3130 
3131     // setup pointer for outgoing packet buffer
3132     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3133 
3134     // max acl payload size defined in config.h
3135     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3136 
3137     // register packet handlers with transport
3138     transport->register_packet_handler(&packet_handler);
3139 
3140     hci_stack->state = HCI_STATE_OFF;
3141 
3142     // class of device
3143     hci_stack->class_of_device = 0x007a020c; // Smartphone
3144 
3145     // bondable by default
3146     hci_stack->bondable = 1;
3147 
3148 #ifdef ENABLE_CLASSIC
3149     // classic name
3150     hci_stack->local_name = default_classic_name;
3151 
3152     // Master slave policy
3153     hci_stack->master_slave_policy = 1;
3154 
3155     // Allow Role Switch
3156     hci_stack->allow_role_switch = 1;
3157 
3158     // Default / minimum security level = 2
3159     hci_stack->gap_security_level = LEVEL_2;
3160 
3161     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3162     hci_stack->gap_required_encyrption_key_size = 7;
3163 #endif
3164 
3165     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3166     hci_stack->ssp_enable = 1;
3167     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3168     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3169     hci_stack->ssp_auto_accept = 1;
3170 
3171     // Secure Connections: enable (requires support from Controller)
3172     hci_stack->secure_connections_enable = true;
3173 
3174     // voice setting - signed 16 bit pcm data with CVSD over the air
3175     hci_stack->sco_voice_setting = 0x60;
3176 
3177 #ifdef ENABLE_LE_CENTRAL
3178     // connection parameter to use for outgoing connections
3179     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3180     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3181     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3182     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3183     hci_stack->le_connection_latency      = 4;         // 4
3184     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3185     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3186     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3187 
3188     // default LE Scanning
3189     hci_stack->le_scan_type     =   0x1; // active
3190     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3191     hci_stack->le_scan_window   =  0x30; //  30 ms
3192 #endif
3193 
3194 #ifdef ENABLE_LE_PERIPHERAL
3195     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3196 #endif
3197 
3198     // connection parameter range used to answer connection parameter update requests in l2cap
3199     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3200     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3201     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3202     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3203     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3204     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3205 
3206     hci_state_reset();
3207 }
3208 
3209 void hci_deinit(void){
3210 #ifdef HAVE_MALLOC
3211     if (hci_stack) {
3212         free(hci_stack);
3213     }
3214 #endif
3215     hci_stack = NULL;
3216 
3217 #ifdef ENABLE_CLASSIC
3218     disable_l2cap_timeouts = 0;
3219 #endif
3220 }
3221 
3222 /**
3223  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3224  */
3225 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3226     hci_stack->chipset = chipset_driver;
3227 
3228     // reset chipset driver - init is also called on power_up
3229     if (hci_stack->chipset && hci_stack->chipset->init){
3230         hci_stack->chipset->init(hci_stack->config);
3231     }
3232 }
3233 
3234 /**
3235  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3236  */
3237 void hci_set_control(const btstack_control_t *hardware_control){
3238     // references to used control implementation
3239     hci_stack->control = hardware_control;
3240     // init with transport config
3241     hardware_control->init(hci_stack->config);
3242 }
3243 
3244 void hci_close(void){
3245     // close remote device db
3246     if (hci_stack->link_key_db) {
3247         hci_stack->link_key_db->close();
3248     }
3249 
3250     btstack_linked_list_iterator_t lit;
3251     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3252     while (btstack_linked_list_iterator_has_next(&lit)){
3253         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3254         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3255         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3256         hci_shutdown_connection(connection);
3257     }
3258 
3259     hci_power_control(HCI_POWER_OFF);
3260 
3261 #ifdef HAVE_MALLOC
3262     free(hci_stack);
3263 #endif
3264     hci_stack = NULL;
3265 }
3266 
3267 #ifdef HAVE_SCO_TRANSPORT
3268 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3269     hci_stack->sco_transport = sco_transport;
3270     sco_transport->register_packet_handler(&packet_handler);
3271 }
3272 #endif
3273 
3274 #ifdef ENABLE_CLASSIC
3275 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3276     // validate ranage and set
3277     if (encryption_key_size < 7)  return;
3278     if (encryption_key_size > 16) return;
3279     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3280 }
3281 
3282 void gap_set_security_level(gap_security_level_t security_level){
3283     hci_stack->gap_security_level = security_level;
3284 }
3285 
3286 gap_security_level_t gap_get_security_level(void){
3287     return hci_stack->gap_security_level;
3288 }
3289 #endif
3290 
3291 #ifdef ENABLE_CLASSIC
3292 void gap_set_class_of_device(uint32_t class_of_device){
3293     hci_stack->class_of_device = class_of_device;
3294 }
3295 
3296 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3297     hci_stack->default_link_policy_settings = default_link_policy_settings;
3298 }
3299 
3300 void gap_set_allow_role_switch(bool allow_role_switch){
3301     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3302 }
3303 
3304 uint8_t hci_get_allow_role_switch(void){
3305     return  hci_stack->allow_role_switch;
3306 }
3307 
3308 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
3309     hci_stack->link_supervision_timeout = link_supervision_timeout;
3310 }
3311 
3312 void hci_disable_l2cap_timeout_check(void){
3313     disable_l2cap_timeouts = 1;
3314 }
3315 #endif
3316 
3317 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3318 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3319 void hci_set_bd_addr(bd_addr_t addr){
3320     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3321     hci_stack->custom_bd_addr_set = 1;
3322 }
3323 #endif
3324 
3325 // State-Module-Driver overview
3326 // state                    module  low-level
3327 // HCI_STATE_OFF             off      close
3328 // HCI_STATE_INITIALIZING,   on       open
3329 // HCI_STATE_WORKING,        on       open
3330 // HCI_STATE_HALTING,        on       open
3331 // HCI_STATE_SLEEPING,    off/sleep   close
3332 // HCI_STATE_FALLING_ASLEEP  on       open
3333 
3334 static int hci_power_control_on(void){
3335 
3336     // power on
3337     int err = 0;
3338     if (hci_stack->control && hci_stack->control->on){
3339         err = (*hci_stack->control->on)();
3340     }
3341     if (err){
3342         log_error( "POWER_ON failed");
3343         hci_emit_hci_open_failed();
3344         return err;
3345     }
3346 
3347     // int chipset driver
3348     if (hci_stack->chipset && hci_stack->chipset->init){
3349         hci_stack->chipset->init(hci_stack->config);
3350     }
3351 
3352     // init transport
3353     if (hci_stack->hci_transport->init){
3354         hci_stack->hci_transport->init(hci_stack->config);
3355     }
3356 
3357     // open transport
3358     err = hci_stack->hci_transport->open();
3359     if (err){
3360         log_error( "HCI_INIT failed, turning Bluetooth off again");
3361         if (hci_stack->control && hci_stack->control->off){
3362             (*hci_stack->control->off)();
3363         }
3364         hci_emit_hci_open_failed();
3365         return err;
3366     }
3367     return 0;
3368 }
3369 
3370 static void hci_power_control_off(void){
3371 
3372     log_info("hci_power_control_off");
3373 
3374     // close low-level device
3375     hci_stack->hci_transport->close();
3376 
3377     log_info("hci_power_control_off - hci_transport closed");
3378 
3379     // power off
3380     if (hci_stack->control && hci_stack->control->off){
3381         (*hci_stack->control->off)();
3382     }
3383 
3384     log_info("hci_power_control_off - control closed");
3385 
3386     hci_stack->state = HCI_STATE_OFF;
3387 }
3388 
3389 static void hci_power_control_sleep(void){
3390 
3391     log_info("hci_power_control_sleep");
3392 
3393 #if 0
3394     // don't close serial port during sleep
3395 
3396     // close low-level device
3397     hci_stack->hci_transport->close(hci_stack->config);
3398 #endif
3399 
3400     // sleep mode
3401     if (hci_stack->control && hci_stack->control->sleep){
3402         (*hci_stack->control->sleep)();
3403     }
3404 
3405     hci_stack->state = HCI_STATE_SLEEPING;
3406 }
3407 
3408 static int hci_power_control_wake(void){
3409 
3410     log_info("hci_power_control_wake");
3411 
3412     // wake on
3413     if (hci_stack->control && hci_stack->control->wake){
3414         (*hci_stack->control->wake)();
3415     }
3416 
3417 #if 0
3418     // open low-level device
3419     int err = hci_stack->hci_transport->open(hci_stack->config);
3420     if (err){
3421         log_error( "HCI_INIT failed, turning Bluetooth off again");
3422         if (hci_stack->control && hci_stack->control->off){
3423             (*hci_stack->control->off)();
3424         }
3425         hci_emit_hci_open_failed();
3426         return err;
3427     }
3428 #endif
3429 
3430     return 0;
3431 }
3432 
3433 static void hci_power_transition_to_initializing(void){
3434     // set up state machine
3435     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
3436     hci_stack->hci_packet_buffer_reserved = 0;
3437     hci_stack->state = HCI_STATE_INITIALIZING;
3438     hci_stack->substate = HCI_INIT_SEND_RESET;
3439 }
3440 
3441 // returns error
3442 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
3443     int err;
3444     switch (power_mode){
3445         case HCI_POWER_ON:
3446             err = hci_power_control_on();
3447             if (err != 0) {
3448                 log_error("hci_power_control_on() error %d", err);
3449                 return err;
3450             }
3451             hci_power_transition_to_initializing();
3452             break;
3453         case HCI_POWER_OFF:
3454             // do nothing
3455             break;
3456         case HCI_POWER_SLEEP:
3457             // do nothing (with SLEEP == OFF)
3458             break;
3459         default:
3460             btstack_assert(false);
3461             break;
3462     }
3463     return ERROR_CODE_SUCCESS;
3464 }
3465 
3466 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
3467     switch (power_mode){
3468         case HCI_POWER_ON:
3469             // do nothing
3470             break;
3471         case HCI_POWER_OFF:
3472             // no connections yet, just turn it off
3473             hci_power_control_off();
3474             break;
3475         case HCI_POWER_SLEEP:
3476             // no connections yet, just turn it off
3477             hci_power_control_sleep();
3478             break;
3479         default:
3480             btstack_assert(false);
3481             break;
3482     }
3483     return ERROR_CODE_SUCCESS;
3484 }
3485 
3486 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
3487     switch (power_mode){
3488         case HCI_POWER_ON:
3489             // do nothing
3490             break;
3491         case HCI_POWER_OFF:
3492             // see hci_run
3493             hci_stack->state = HCI_STATE_HALTING;
3494             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3495             break;
3496         case HCI_POWER_SLEEP:
3497             // see hci_run
3498             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3499             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3500             break;
3501         default:
3502             btstack_assert(false);
3503             break;
3504     }
3505     return ERROR_CODE_SUCCESS;
3506 }
3507 
3508 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
3509     switch (power_mode){
3510         case HCI_POWER_ON:
3511             hci_power_transition_to_initializing();
3512             break;
3513         case HCI_POWER_OFF:
3514             // do nothing
3515             break;
3516         case HCI_POWER_SLEEP:
3517             // see hci_run
3518             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3519             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3520             break;
3521         default:
3522             btstack_assert(false);
3523             break;
3524     }
3525     return ERROR_CODE_SUCCESS;
3526 }
3527 
3528 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
3529     switch (power_mode){
3530         case HCI_POWER_ON:
3531 
3532 #ifdef HAVE_PLATFORM_IPHONE_OS
3533             // nothing to do, if H4 supports power management
3534                     if (btstack_control_iphone_power_management_enabled()){
3535                         hci_stack->state = HCI_STATE_INITIALIZING;
3536                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3537                         break;
3538                     }
3539 #endif
3540             hci_power_transition_to_initializing();
3541             break;
3542         case HCI_POWER_OFF:
3543             // see hci_run
3544             hci_stack->state = HCI_STATE_HALTING;
3545             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3546             break;
3547         case HCI_POWER_SLEEP:
3548             // do nothing
3549             break;
3550         default:
3551             btstack_assert(false);
3552             break;
3553     }
3554     return ERROR_CODE_SUCCESS;
3555 }
3556 
3557 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
3558     int err;
3559     switch (power_mode){
3560         case HCI_POWER_ON:
3561 #ifdef HAVE_PLATFORM_IPHONE_OS
3562             // nothing to do, if H4 supports power management
3563                     if (btstack_control_iphone_power_management_enabled()){
3564                         hci_stack->state = HCI_STATE_INITIALIZING;
3565                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3566                         hci_update_scan_enable();
3567                         break;
3568                     }
3569 #endif
3570             err = hci_power_control_wake();
3571             if (err) return err;
3572             hci_power_transition_to_initializing();
3573             break;
3574         case HCI_POWER_OFF:
3575             hci_stack->state = HCI_STATE_HALTING;
3576             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3577             break;
3578         case HCI_POWER_SLEEP:
3579             // do nothing
3580             break;
3581         default:
3582             btstack_assert(false);
3583             break;
3584     }
3585     return ERROR_CODE_SUCCESS;
3586 }
3587 
3588 int hci_power_control(HCI_POWER_MODE power_mode){
3589     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
3590     int err = 0;
3591     switch (hci_stack->state){
3592         case HCI_STATE_OFF:
3593             err = hci_power_control_state_off(power_mode);
3594             break;
3595         case HCI_STATE_INITIALIZING:
3596             err = hci_power_control_state_initializing(power_mode);
3597             break;
3598         case HCI_STATE_WORKING:
3599             err = hci_power_control_state_working(power_mode);
3600             break;
3601         case HCI_STATE_HALTING:
3602             err = hci_power_control_state_halting(power_mode);
3603             break;
3604         case HCI_STATE_FALLING_ASLEEP:
3605             err = hci_power_control_state_falling_asleep(power_mode);
3606             break;
3607         case HCI_STATE_SLEEPING:
3608             err = hci_power_control_state_sleeping(power_mode);
3609             break;
3610         default:
3611             btstack_assert(false);
3612             break;
3613     }
3614     if (err != 0){
3615         return err;
3616     }
3617 
3618     // create internal event
3619 	hci_emit_state();
3620 
3621 	// trigger next/first action
3622 	hci_run();
3623 
3624     return 0;
3625 }
3626 
3627 
3628 #ifdef ENABLE_CLASSIC
3629 
3630 static void hci_update_scan_enable(void){
3631     // 2 = page scan, 1 = inq scan
3632     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
3633     hci_run();
3634 }
3635 
3636 void gap_discoverable_control(uint8_t enable){
3637     if (enable) enable = 1; // normalize argument
3638 
3639     if (hci_stack->discoverable == enable){
3640         hci_emit_discoverable_enabled(hci_stack->discoverable);
3641         return;
3642     }
3643 
3644     hci_stack->discoverable = enable;
3645     hci_update_scan_enable();
3646 }
3647 
3648 void gap_connectable_control(uint8_t enable){
3649     if (enable) enable = 1; // normalize argument
3650 
3651     // don't emit event
3652     if (hci_stack->connectable == enable) return;
3653 
3654     hci_stack->connectable = enable;
3655     hci_update_scan_enable();
3656 }
3657 #endif
3658 
3659 void gap_local_bd_addr(bd_addr_t address_buffer){
3660     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3661 }
3662 
3663 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3664 static void hci_host_num_completed_packets(void){
3665 
3666     // create packet manually as arrays are not supported and num_commands should not get reduced
3667     hci_reserve_packet_buffer();
3668     uint8_t * packet = hci_get_outgoing_packet_buffer();
3669 
3670     uint16_t size = 0;
3671     uint16_t num_handles = 0;
3672     packet[size++] = 0x35;
3673     packet[size++] = 0x0c;
3674     size++;  // skip param len
3675     size++;  // skip num handles
3676 
3677     // add { handle, packets } entries
3678     btstack_linked_item_t * it;
3679     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3680         hci_connection_t * connection = (hci_connection_t *) it;
3681         if (connection->num_packets_completed){
3682             little_endian_store_16(packet, size, connection->con_handle);
3683             size += 2;
3684             little_endian_store_16(packet, size, connection->num_packets_completed);
3685             size += 2;
3686             //
3687             num_handles++;
3688             connection->num_packets_completed = 0;
3689         }
3690     }
3691 
3692     packet[2] = size - 3;
3693     packet[3] = num_handles;
3694 
3695     hci_stack->host_completed_packets = 0;
3696 
3697     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3698     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3699 
3700     // release packet buffer for synchronous transport implementations
3701     if (hci_transport_synchronous()){
3702         hci_release_packet_buffer();
3703         hci_emit_transport_packet_sent();
3704     }
3705 }
3706 #endif
3707 
3708 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
3709     UNUSED(ds);
3710     hci_stack->substate = HCI_HALTING_CLOSE;
3711     // allow packet handlers to defer final shutdown
3712     hci_emit_state();
3713     hci_run();
3714 }
3715 
3716 static bool hci_run_acl_fragments(void){
3717     if (hci_stack->acl_fragmentation_total_size > 0u) {
3718         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3719         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3720         if (connection) {
3721             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3722                 hci_send_acl_packet_fragments(connection);
3723                 return true;
3724             }
3725         } else {
3726             // connection gone -> discard further fragments
3727             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3728             hci_stack->acl_fragmentation_total_size = 0;
3729             hci_stack->acl_fragmentation_pos = 0;
3730         }
3731     }
3732     return false;
3733 }
3734 
3735 #ifdef ENABLE_CLASSIC
3736 static bool hci_run_general_gap_classic(void){
3737 
3738     // decline incoming connections
3739     if (hci_stack->decline_reason){
3740         uint8_t reason = hci_stack->decline_reason;
3741         hci_stack->decline_reason = 0;
3742         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3743         return true;
3744     }
3745     // send scan enable
3746     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_scan_enable_value != 0xff) && hci_classic_supported()){
3747         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3748         hci_stack->new_scan_enable_value = 0xff;
3749         return true;
3750     }
3751     // start/stop inquiry
3752     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
3753         uint8_t duration = hci_stack->inquiry_state;
3754         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3755         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3756         return true;
3757     }
3758     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3759         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3760         hci_send_cmd(&hci_inquiry_cancel);
3761         return true;
3762     }
3763     // remote name request
3764     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3765         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3766         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3767                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3768         return true;
3769     }
3770 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3771     // Local OOB data
3772     if ((hci_stack->state == HCI_STATE_WORKING) && hci_stack->classic_read_local_oob_data){
3773         hci_stack->classic_read_local_oob_data = false;
3774         if (hci_stack->local_supported_commands[1] & 0x10u){
3775             hci_send_cmd(&hci_read_local_extended_oob_data);
3776         } else {
3777             hci_send_cmd(&hci_read_local_oob_data);
3778         }
3779     }
3780 #endif
3781     // pairing
3782     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3783         uint8_t state = hci_stack->gap_pairing_state;
3784         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3785         switch (state){
3786             case GAP_PAIRING_STATE_SEND_PIN:
3787                 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);
3788                 break;
3789             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3790                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3791                 break;
3792             case GAP_PAIRING_STATE_SEND_PASSKEY:
3793                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3794                 break;
3795             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3796                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3797                 break;
3798             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3799                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3800                 break;
3801             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3802                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3803                 break;
3804             default:
3805                 break;
3806         }
3807         return true;
3808     }
3809     return false;
3810 }
3811 #endif
3812 
3813 #ifdef ENABLE_BLE
3814 static bool hci_run_general_gap_le(void){
3815 
3816     // advertisements, active scanning, and creating connections requires random address to be set if using private address
3817 
3818     if (hci_stack->state != HCI_STATE_WORKING) return false;
3819     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
3820 
3821 
3822     // Phase 1: collect what to stop
3823 
3824     bool scanning_stop = false;
3825     bool connecting_stop = false;
3826     bool advertising_stop = false;
3827 
3828 #ifndef ENABLE_LE_CENTRAL
3829     UNUSED(scanning_stop);
3830     UNUSED(connecting_stop);
3831 #endif
3832 #ifndef ENABLE_LE_PERIPHERAL
3833     UNUSED(advertising_stop);
3834 #endif
3835 
3836     // check if whitelist needs modification
3837     bool whitelist_modification_pending = false;
3838     btstack_linked_list_iterator_t lit;
3839     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3840     while (btstack_linked_list_iterator_has_next(&lit)){
3841         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3842         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3843             whitelist_modification_pending = true;
3844             break;
3845         }
3846     }
3847     // check if resolving list needs modification
3848     bool resolving_list_modification_pending = false;
3849 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
3850     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
3851 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
3852         resolving_list_modification_pending = true;
3853     }
3854 #endif
3855 
3856 #ifdef ENABLE_LE_CENTRAL
3857     // scanning control
3858     if (hci_stack->le_scanning_active) {
3859         // stop if:
3860         // - parameter change required
3861         // - it's disabled
3862         // - whitelist change required but used for scanning
3863         // - resolving list modified
3864         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
3865         if ((hci_stack->le_scanning_param_update) ||
3866             !hci_stack->le_scanning_enabled ||
3867             scanning_uses_whitelist ||
3868             resolving_list_modification_pending){
3869 
3870             scanning_stop = true;
3871         }
3872     }
3873 #endif
3874 
3875 #ifdef ENABLE_LE_CENTRAL
3876     // connecting control
3877     bool connecting_with_whitelist;
3878     switch (hci_stack->le_connecting_state){
3879         case LE_CONNECTING_DIRECT:
3880         case LE_CONNECTING_WHITELIST:
3881             // stop connecting if:
3882             // - connecting uses white and whitelist modification pending
3883             // - if it got disabled
3884             // - resolving list modified
3885             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
3886             if ((connecting_with_whitelist && whitelist_modification_pending) ||
3887                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
3888                 resolving_list_modification_pending) {
3889 
3890                 connecting_stop = true;
3891             }
3892             break;
3893         default:
3894             break;
3895     }
3896 #endif
3897 
3898 #ifdef ENABLE_LE_PERIPHERAL
3899     // le advertisement control
3900     if (hci_stack->le_advertisements_active){
3901         // stop if:
3902         // - parameter change required
3903         // - it's disabled
3904         // - whitelist change required but used for advertisement filter policy
3905         // - resolving list modified
3906         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy > 0;
3907         if ((hci_stack->le_advertisements_todo != 0) ||
3908             !hci_stack->le_advertisements_enabled_for_current_roles ||
3909             (advertising_uses_whitelist & whitelist_modification_pending) ||
3910             resolving_list_modification_pending) {
3911 
3912             advertising_stop = true;
3913         }
3914     }
3915 #endif
3916 
3917 
3918     // Phase 2: stop everything that should be off during modifications
3919 
3920 #ifdef ENABLE_LE_CENTRAL
3921     if (scanning_stop){
3922         hci_stack->le_scanning_active = false;
3923         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
3924         return true;
3925     }
3926 #endif
3927 
3928 #ifdef ENABLE_LE_CENTRAL
3929     if (connecting_stop){
3930         hci_send_cmd(&hci_le_create_connection_cancel);
3931         return true;
3932     }
3933 #endif
3934 
3935 #ifdef ENABLE_LE_PERIPHERAL
3936     if (advertising_stop){
3937         hci_stack->le_advertisements_active = false;
3938         hci_send_cmd(&hci_le_set_advertise_enable, 0);
3939         return true;
3940     }
3941 #endif
3942 
3943     // Phase 3: modify
3944 
3945 #ifdef ENABLE_LE_CENTRAL
3946     if (hci_stack->le_scanning_param_update){
3947         hci_stack->le_scanning_param_update = false;
3948         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
3949                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
3950         return true;
3951     }
3952 #endif
3953 
3954 #ifdef ENABLE_LE_PERIPHERAL
3955     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3956         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3957         hci_send_cmd(&hci_le_set_advertising_parameters,
3958                      hci_stack->le_advertisements_interval_min,
3959                      hci_stack->le_advertisements_interval_max,
3960                      hci_stack->le_advertisements_type,
3961                      hci_stack->le_own_addr_type,
3962                      hci_stack->le_advertisements_direct_address_type,
3963                      hci_stack->le_advertisements_direct_address,
3964                      hci_stack->le_advertisements_channel_map,
3965                      hci_stack->le_advertisements_filter_policy);
3966         return true;
3967     }
3968     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3969         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3970         uint8_t adv_data_clean[31];
3971         memset(adv_data_clean, 0, sizeof(adv_data_clean));
3972         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
3973                      hci_stack->le_advertisements_data_len);
3974         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
3975         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3976         return true;
3977     }
3978     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3979         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3980         uint8_t scan_data_clean[31];
3981         memset(scan_data_clean, 0, sizeof(scan_data_clean));
3982         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
3983                      hci_stack->le_scan_response_data_len);
3984         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
3985         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
3986         return true;
3987     }
3988 #endif
3989 
3990 
3991 #ifdef ENABLE_LE_CENTRAL
3992     // if connect with whitelist was active and is not cancelled yet, wait until next time
3993     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
3994 #endif
3995 
3996     // LE Whitelist Management
3997     if (whitelist_modification_pending){
3998         // add/remove entries
3999         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4000         while (btstack_linked_list_iterator_has_next(&lit)){
4001             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4002 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4003 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4004 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
4005 				return true;
4006 			}
4007             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
4008 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
4009                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
4010                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
4011                 return true;
4012             }
4013             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
4014 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4015 				btstack_memory_whitelist_entry_free(entry);
4016             }
4017         }
4018     }
4019 
4020 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4021     // LE Resolving List Management
4022     if (resolving_list_supported) {
4023 		uint16_t i;
4024 		switch (hci_stack->le_resolving_list_state) {
4025 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
4026 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
4027 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
4028 				return true;
4029 			case LE_RESOLVING_LIST_READ_SIZE:
4030 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
4031 				hci_send_cmd(&hci_le_read_resolving_list_size);
4032 				return true;
4033 			case LE_RESOLVING_LIST_SEND_CLEAR:
4034 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4035 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4036 							  sizeof(hci_stack->le_resolving_list_add_entries));
4037 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4038 							  sizeof(hci_stack->le_resolving_list_remove_entries));
4039 				hci_send_cmd(&hci_le_clear_resolving_list);
4040 				return true;
4041 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
4042 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4043 					uint8_t offset = i >> 3;
4044 					uint8_t mask = 1 << (i & 7);
4045 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
4046 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
4047 					bd_addr_t peer_identity_addreses;
4048 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4049 					sm_key_t peer_irk;
4050 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4051 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4052 
4053 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4054 					// trigger whitelist entry 'update' (work around for controller bug)
4055 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4056 					while (btstack_linked_list_iterator_has_next(&lit)) {
4057 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4058 						if (entry->address_type != peer_identity_addr_type) continue;
4059 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4060 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4061 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4062 					}
4063 #endif
4064 
4065 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4066 								 peer_identity_addreses);
4067 					return true;
4068 				}
4069 
4070 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
4071 
4072 				/* fall through */
4073 
4074 			case LE_RESOLVING_LIST_ADD_ENTRIES:
4075 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4076 					uint8_t offset = i >> 3;
4077 					uint8_t mask = 1 << (i & 7);
4078 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
4079 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
4080 					bd_addr_t peer_identity_addreses;
4081 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4082 					sm_key_t peer_irk;
4083 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4084 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4085 					const uint8_t *local_irk = gap_get_persistent_irk();
4086 					// command uses format specifier 'P' that stores 16-byte value without flip
4087 					uint8_t local_irk_flipped[16];
4088 					uint8_t peer_irk_flipped[16];
4089 					reverse_128(local_irk, local_irk_flipped);
4090 					reverse_128(peer_irk, peer_irk_flipped);
4091 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4092 								 peer_irk_flipped, local_irk_flipped);
4093 					return true;
4094 				}
4095 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4096 				break;
4097 
4098 			default:
4099 				break;
4100 		}
4101 	}
4102     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4103 #endif
4104 
4105     // Phase 4: restore state
4106 
4107 #ifdef ENABLE_LE_CENTRAL
4108     // re-start scanning
4109     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
4110         hci_stack->le_scanning_active = true;
4111         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
4112         return true;
4113     }
4114 #endif
4115 
4116 #ifdef ENABLE_LE_CENTRAL
4117     // re-start connecting
4118     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
4119         bd_addr_t null_addr;
4120         memset(null_addr, 0, 6);
4121         hci_send_cmd(&hci_le_create_connection,
4122                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4123                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
4124                      1,         // use whitelist
4125                      0,         // peer address type
4126                      null_addr, // peer bd addr
4127                      hci_stack->le_own_addr_type, // our addr type:
4128                      hci_stack->le_connection_interval_min,    // conn interval min
4129                      hci_stack->le_connection_interval_max,    // conn interval max
4130                      hci_stack->le_connection_latency,         // conn latency
4131                      hci_stack->le_supervision_timeout,        // conn latency
4132                      hci_stack->le_minimum_ce_length,          // min ce length
4133                      hci_stack->le_maximum_ce_length           // max ce length
4134         );
4135         return true;
4136     }
4137 #endif
4138 
4139 #ifdef ENABLE_LE_PERIPHERAL
4140     // re-start advertising
4141     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4142         // check if advertisements should be enabled given
4143         hci_stack->le_advertisements_active = true;
4144         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4145         return true;
4146     }
4147 #endif
4148 
4149     return false;
4150 }
4151 #endif
4152 
4153 static bool hci_run_general_pending_commands(void){
4154     btstack_linked_item_t * it;
4155     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
4156         hci_connection_t * connection = (hci_connection_t *) it;
4157 
4158         switch(connection->state){
4159             case SEND_CREATE_CONNECTION:
4160                 switch(connection->address_type){
4161 #ifdef ENABLE_CLASSIC
4162                     case BD_ADDR_TYPE_ACL:
4163                         log_info("sending hci_create_connection");
4164                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
4165                         break;
4166 #endif
4167                     default:
4168 #ifdef ENABLE_BLE
4169 #ifdef ENABLE_LE_CENTRAL
4170                         log_info("sending hci_le_create_connection");
4171                         hci_send_cmd(&hci_le_create_connection,
4172                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4173                                      hci_stack->le_connection_scan_window,      // conn scan windows
4174                                      0,         // don't use whitelist
4175                                      connection->address_type, // peer address type
4176                                      connection->address,      // peer bd addr
4177                                      hci_stack->le_own_addr_type, // our addr type:
4178                                      hci_stack->le_connection_interval_min,    // conn interval min
4179                                      hci_stack->le_connection_interval_max,    // conn interval max
4180                                      hci_stack->le_connection_latency,         // conn latency
4181                                      hci_stack->le_supervision_timeout,        // conn latency
4182                                      hci_stack->le_minimum_ce_length,          // min ce length
4183                                      hci_stack->le_maximum_ce_length          // max ce length
4184                         );
4185                         connection->state = SENT_CREATE_CONNECTION;
4186 #endif
4187 #endif
4188                         break;
4189                 }
4190                 return true;
4191 
4192 #ifdef ENABLE_CLASSIC
4193             case RECEIVED_CONNECTION_REQUEST:
4194                 connection->role  = HCI_ROLE_SLAVE;
4195                 if (connection->address_type == BD_ADDR_TYPE_ACL){
4196                     log_info("sending hci_accept_connection_request");
4197                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4198                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4199                 }
4200                 return true;
4201 #endif
4202 
4203 #ifdef ENABLE_BLE
4204 #ifdef ENABLE_LE_CENTRAL
4205             case SEND_CANCEL_CONNECTION:
4206                 connection->state = SENT_CANCEL_CONNECTION;
4207                 hci_send_cmd(&hci_le_create_connection_cancel);
4208                 return true;
4209 #endif
4210 #endif
4211             case SEND_DISCONNECT:
4212                 connection->state = SENT_DISCONNECT;
4213                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4214                 return true;
4215 
4216             default:
4217                 break;
4218         }
4219 
4220         // no further commands if connection is about to get shut down
4221         if (connection->state == SENT_DISCONNECT) continue;
4222 
4223         if (connection->authentication_flags & READ_RSSI){
4224             connectionClearAuthenticationFlags(connection, READ_RSSI);
4225             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4226             return true;
4227         }
4228 
4229 #ifdef ENABLE_CLASSIC
4230 
4231         if (connection->authentication_flags & WRITE_SUPERVISION_TIMEOUT){
4232             connectionClearAuthenticationFlags(connection, WRITE_SUPERVISION_TIMEOUT);
4233             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4234             return true;
4235         }
4236 
4237         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
4238             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
4239             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
4240 
4241             link_key_t link_key;
4242             link_key_type_t link_key_type;
4243             bool have_link_key = hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type);
4244 
4245             const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
4246             bool sc_enabled_remote = (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
4247             bool sc_downgrade = have_link_key && (gap_secure_connection_for_link_key_type(link_key_type) == 1) && !sc_enabled_remote;
4248             if (sc_downgrade){
4249                 log_info("Link key based on SC, but remote does not support SC -> disconnect");
4250                 connection->state = SENT_DISCONNECT;
4251                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4252                 return true;
4253             }
4254 
4255             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level);
4256             if (have_link_key && security_level_sufficient){
4257                 connection->link_key_type = link_key_type;
4258                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
4259             } else {
4260                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
4261             }
4262             return true;
4263         }
4264 
4265         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
4266             log_info("denying to pin request");
4267             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
4268             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4269             return true;
4270         }
4271 
4272         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
4273             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
4274             // tweak authentication requirements
4275             uint8_t authreq = hci_stack->ssp_authentication_requirement;
4276             if (connection->bonding_flags & BONDING_DEDICATED){
4277                 authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4278             }
4279             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
4280                 authreq |= 1;
4281             }
4282             uint8_t have_oob_data = 0;
4283 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4284             if (connection->classic_oob_c_192 != NULL){
4285                     have_oob_data |= 1;
4286             }
4287             if (connection->classic_oob_c_256 != NULL){
4288                 have_oob_data |= 2;
4289             }
4290 #endif
4291             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
4292             return true;
4293         }
4294 
4295         if (connection->authentication_flags & SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
4296             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
4297             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4298             return true;
4299         }
4300 
4301 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4302         if (connection->authentication_flags & SEND_REMOTE_OOB_DATA_REPLY){
4303             connectionClearAuthenticationFlags(connection, SEND_REMOTE_OOB_DATA_REPLY);
4304             const uint8_t zero[16] = { 0 };
4305             const uint8_t * r_192 = zero;
4306             const uint8_t * c_192 = zero;
4307             const uint8_t * r_256 = zero;
4308             const uint8_t * c_256 = zero;
4309             // verify P-256 OOB
4310             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
4311                 c_256 = connection->classic_oob_c_256;
4312                 if (connection->classic_oob_r_256 != NULL) {
4313                     r_256 = connection->classic_oob_r_256;
4314                 }
4315             }
4316             // verify P-192 OOB
4317             if ((connection->classic_oob_c_192 != NULL)) {
4318                 c_192 = connection->classic_oob_c_192;
4319                 if (connection->classic_oob_r_192 != NULL) {
4320                     r_192 = connection->classic_oob_r_192;
4321                 }
4322             }
4323             // Reply
4324             if (c_256 != zero) {
4325                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
4326             } else if (c_192 != zero){
4327                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
4328             } else {
4329                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
4330             }
4331             return true;
4332         }
4333 #endif
4334 
4335         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
4336             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
4337             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4338             return true;
4339         }
4340 
4341         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
4342             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
4343             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4344             return true;
4345         }
4346 
4347         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4348             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
4349             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4350             return true;
4351         }
4352 
4353         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
4354             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
4355             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
4356             return true;
4357         }
4358 
4359         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
4360             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
4361             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
4362             return true;
4363         }
4364 
4365         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4366             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
4367             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
4368             connection->state = SENT_DISCONNECT;
4369             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4370             return true;
4371         }
4372 
4373         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
4374             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4375             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
4376             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4377             return true;
4378         }
4379 
4380         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4381             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4382             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4383             return true;
4384         }
4385         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4386             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4387             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4388             return true;
4389         }
4390 #endif
4391 
4392         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
4393             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
4394             if (connection->state != SENT_DISCONNECT){
4395                 connection->state = SENT_DISCONNECT;
4396                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4397                 return true;
4398             }
4399         }
4400 
4401 #ifdef ENABLE_CLASSIC
4402         uint16_t sniff_min_interval;
4403         switch (connection->sniff_min_interval){
4404             case 0:
4405                 break;
4406             case 0xffff:
4407                 connection->sniff_min_interval = 0;
4408                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4409                 return true;
4410             default:
4411                 sniff_min_interval = connection->sniff_min_interval;
4412                 connection->sniff_min_interval = 0;
4413                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4414                 return true;
4415         }
4416 
4417         if (connection->request_role != HCI_ROLE_INVALID){
4418             hci_role_t  role = connection->request_role;
4419             connection->request_role = HCI_ROLE_INVALID;
4420             hci_send_cmd(&hci_switch_role_command, connection->address, role);
4421             return true;
4422         }
4423 #endif
4424 
4425 #ifdef ENABLE_BLE
4426         switch (connection->le_con_parameter_update_state){
4427             // response to L2CAP CON PARAMETER UPDATE REQUEST
4428             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4429                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4430                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4431                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4432                              0x0000, 0xffff);
4433                 return true;
4434             case CON_PARAMETER_UPDATE_REPLY:
4435                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4436                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, 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_NEGATIVE_REPLY:
4441                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4442                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4443                 return true;
4444             default:
4445                 break;
4446         }
4447         if (connection->le_phy_update_all_phys != 0xffu){
4448             uint8_t all_phys = connection->le_phy_update_all_phys;
4449             connection->le_phy_update_all_phys = 0xff;
4450             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);
4451             return true;
4452         }
4453 #endif
4454     }
4455     return false;
4456 }
4457 
4458 static void hci_run(void){
4459 
4460     bool done;
4461 
4462     // send continuation fragments first, as they block the prepared packet buffer
4463     done = hci_run_acl_fragments();
4464     if (done) return;
4465 
4466 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4467     // send host num completed packets next as they don't require num_cmd_packets > 0
4468     if (!hci_can_send_comand_packet_transport()) return;
4469     if (hci_stack->host_completed_packets){
4470         hci_host_num_completed_packets();
4471         return;
4472     }
4473 #endif
4474 
4475     if (!hci_can_send_command_packet_now()) return;
4476 
4477     // global/non-connection oriented commands
4478 
4479 
4480 #ifdef ENABLE_CLASSIC
4481     // general gap classic
4482     done = hci_run_general_gap_classic();
4483     if (done) return;
4484 #endif
4485 
4486 #ifdef ENABLE_BLE
4487     // general gap le
4488     done = hci_run_general_gap_le();
4489     if (done) return;
4490 #endif
4491 
4492     // send pending HCI commands
4493     done = hci_run_general_pending_commands();
4494     if (done) return;
4495 
4496     // stack state sub statemachines
4497     hci_connection_t * connection;
4498     switch (hci_stack->state){
4499         case HCI_STATE_INITIALIZING:
4500             hci_initializing_run();
4501             break;
4502 
4503         case HCI_STATE_HALTING:
4504 
4505             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4506             switch (hci_stack->substate){
4507                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
4508                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
4509 
4510 #ifdef ENABLE_BLE
4511 #ifdef ENABLE_LE_CENTRAL
4512                     // free whitelist entries
4513                     {
4514                         btstack_linked_list_iterator_t lit;
4515                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4516                         while (btstack_linked_list_iterator_has_next(&lit)){
4517                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4518                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4519                             btstack_memory_whitelist_entry_free(entry);
4520                         }
4521                     }
4522 #endif
4523 #endif
4524                     // close all open connections
4525                     connection =  (hci_connection_t *) hci_stack->connections;
4526                     if (connection){
4527                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4528                         if (!hci_can_send_command_packet_now()) return;
4529 
4530                         // check state
4531                         if (connection->state == SENT_DISCONNECT) return;
4532                         connection->state = SENT_DISCONNECT;
4533 
4534                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4535 
4536                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
4537                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
4538 
4539                         // ... which would be ignored anyway as we shutdown (free) the connection now
4540                         hci_shutdown_connection(connection);
4541 
4542                         // finally, send the disconnect command
4543                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4544                         return;
4545                     }
4546 
4547                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
4548                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4549                         log_info("HCI_STATE_HALTING: wait 50 ms");
4550                         hci_stack->substate = HCI_HALTING_W4_TIMER;
4551                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4552                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4553                         btstack_run_loop_add_timer(&hci_stack->timeout);
4554                         break;
4555                     }
4556 
4557                     /* fall through */
4558 
4559                 case HCI_HALTING_CLOSE:
4560                     log_info("HCI_STATE_HALTING, calling off");
4561 
4562                     // switch mode
4563                     hci_power_control_off();
4564 
4565                     log_info("HCI_STATE_HALTING, emitting state");
4566                     hci_emit_state();
4567                     log_info("HCI_STATE_HALTING, done");
4568                     break;
4569 
4570                 case HCI_HALTING_W4_TIMER:
4571                     // keep waiting
4572 
4573                     break;
4574                 default:
4575                     break;
4576             }
4577 
4578             break;
4579 
4580         case HCI_STATE_FALLING_ASLEEP:
4581             switch(hci_stack->substate) {
4582                 case HCI_FALLING_ASLEEP_DISCONNECT:
4583                     log_info("HCI_STATE_FALLING_ASLEEP");
4584                     // close all open connections
4585                     connection =  (hci_connection_t *) hci_stack->connections;
4586 
4587 #ifdef HAVE_PLATFORM_IPHONE_OS
4588                     // don't close connections, if H4 supports power management
4589                     if (btstack_control_iphone_power_management_enabled()){
4590                         connection = NULL;
4591                     }
4592 #endif
4593                     if (connection){
4594 
4595                         // send disconnect
4596                         if (!hci_can_send_command_packet_now()) return;
4597 
4598                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
4599                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4600 
4601                         // send disconnected event right away - causes higher layer connections to get closed, too.
4602                         hci_shutdown_connection(connection);
4603                         return;
4604                     }
4605 
4606                     if (hci_classic_supported()){
4607                         // disable page and inquiry scan
4608                         if (!hci_can_send_command_packet_now()) return;
4609 
4610                         log_info("HCI_STATE_HALTING, disabling inq scans");
4611                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
4612 
4613                         // continue in next sub state
4614                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
4615                         break;
4616                     }
4617 
4618                     /* fall through */
4619 
4620                 case HCI_FALLING_ASLEEP_COMPLETE:
4621                     log_info("HCI_STATE_HALTING, calling sleep");
4622 #ifdef HAVE_PLATFORM_IPHONE_OS
4623                     // don't actually go to sleep, if H4 supports power management
4624                     if (btstack_control_iphone_power_management_enabled()){
4625                         // SLEEP MODE reached
4626                         hci_stack->state = HCI_STATE_SLEEPING;
4627                         hci_emit_state();
4628                         break;
4629                     }
4630 #endif
4631                     // switch mode
4632                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
4633                     hci_emit_state();
4634                     break;
4635 
4636                 default:
4637                     break;
4638             }
4639             break;
4640 
4641         default:
4642             break;
4643     }
4644 }
4645 
4646 int hci_send_cmd_packet(uint8_t *packet, int size){
4647     // house-keeping
4648 
4649 #ifdef ENABLE_CLASSIC
4650     bd_addr_t addr;
4651     hci_connection_t * conn;
4652 #endif
4653 #ifdef ENABLE_LE_CENTRAL
4654     uint8_t initiator_filter_policy;
4655 #endif
4656 
4657     uint16_t opcode = little_endian_read_16(packet, 0);
4658     switch (opcode) {
4659         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
4660             hci_stack->loopback_mode = packet[3];
4661             break;
4662 
4663 #ifdef ENABLE_CLASSIC
4664         case HCI_OPCODE_HCI_CREATE_CONNECTION:
4665             reverse_bd_addr(&packet[3], addr);
4666             log_info("Create_connection to %s", bd_addr_to_str(addr));
4667 
4668             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4669             if (!conn) {
4670                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4671                 if (!conn) {
4672                     // notify client that alloc failed
4673                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4674                     return -1; // packet not sent to controller
4675                 }
4676                 conn->state = SEND_CREATE_CONNECTION;
4677                 conn->role  = HCI_ROLE_MASTER;
4678             }
4679             log_info("conn state %u", conn->state);
4680             switch (conn->state) {
4681                 // if connection active exists
4682                 case OPEN:
4683                     // and OPEN, emit connection complete command
4684                     hci_emit_connection_complete(addr, conn->con_handle, 0);
4685                     return -1; // packet not sent to controller
4686                 case RECEIVED_DISCONNECTION_COMPLETE:
4687                     // create connection triggered in disconnect complete event, let's do it now
4688                     break;
4689                 case SEND_CREATE_CONNECTION:
4690                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
4691                     break;
4692                 default:
4693                     // otherwise, just ignore as it is already in the open process
4694                     return -1; // packet not sent to controller
4695             }
4696             conn->state = SENT_CREATE_CONNECTION;
4697 
4698             // track outgoing connection
4699             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
4700             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
4701             break;
4702         case HCI_OPCODE_HCI_LINK_KEY_REQUEST_REPLY:
4703             hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
4704             break;
4705         case HCI_OPCODE_HCI_LINK_KEY_REQUEST_NEGATIVE_REPLY:
4706             hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
4707             break;
4708         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
4709             if (hci_stack->link_key_db) {
4710                 reverse_bd_addr(&packet[3], addr);
4711                 hci_stack->link_key_db->delete_link_key(addr);
4712             }
4713             break;
4714         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
4715         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_REPLY:
4716             reverse_bd_addr(&packet[3], addr);
4717             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4718             if (conn) {
4719                 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
4720             }
4721             break;
4722         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
4723         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_REPLY:
4724         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
4725         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_REPLY:
4726             reverse_bd_addr(&packet[3], addr);
4727             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4728             if (conn) {
4729                 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
4730             }
4731             break;
4732 
4733 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
4734         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
4735             // setup_synchronous_connection? Voice setting at offset 22
4736             // TODO: compare to current setting if sco connection already active
4737             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
4738             break;
4739         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
4740             // accept_synchronus_connection? Voice setting at offset 18
4741             // TODO: compare to current setting if sco connection already active
4742             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
4743             break;
4744 #endif
4745 #endif
4746 
4747 #ifdef ENABLE_BLE
4748         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
4749             hci_stack->le_random_address_set = 1;
4750             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
4751             break;
4752 #ifdef ENABLE_LE_PERIPHERAL
4753         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
4754             hci_stack->le_advertisements_active = packet[3] != 0;
4755             break;
4756 #endif
4757 #ifdef ENABLE_LE_CENTRAL
4758         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
4759             // white list used?
4760             initiator_filter_policy = packet[7];
4761             switch (initiator_filter_policy) {
4762                 case 0:
4763                     // whitelist not used
4764                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
4765                     break;
4766                 case 1:
4767                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
4768                     break;
4769                 default:
4770                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
4771                     break;
4772             }
4773             // track outgoing connection
4774             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
4775             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
4776             break;
4777         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
4778             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
4779             break;
4780 #endif
4781 #endif
4782         default:
4783             break;
4784     }
4785 
4786     hci_stack->num_cmd_packets--;
4787 
4788     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4789     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4790 }
4791 
4792 // disconnect because of security block
4793 void hci_disconnect_security_block(hci_con_handle_t con_handle){
4794     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4795     if (!connection) return;
4796     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4797 }
4798 
4799 
4800 // Configure Secure Simple Pairing
4801 
4802 #ifdef ENABLE_CLASSIC
4803 
4804 // enable will enable SSP during init
4805 void gap_ssp_set_enable(int enable){
4806     hci_stack->ssp_enable = enable;
4807 }
4808 
4809 static int hci_local_ssp_activated(void){
4810     return gap_ssp_supported() && hci_stack->ssp_enable;
4811 }
4812 
4813 // if set, BTstack will respond to io capability request using authentication requirement
4814 void gap_ssp_set_io_capability(int io_capability){
4815     hci_stack->ssp_io_capability = io_capability;
4816 }
4817 void gap_ssp_set_authentication_requirement(int authentication_requirement){
4818     hci_stack->ssp_authentication_requirement = authentication_requirement;
4819 }
4820 
4821 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
4822 void gap_ssp_set_auto_accept(int auto_accept){
4823     hci_stack->ssp_auto_accept = auto_accept;
4824 }
4825 
4826 void gap_secure_connections_enable(bool enable){
4827     hci_stack->secure_connections_enable = enable;
4828 }
4829 
4830 #endif
4831 
4832 // va_list part of hci_send_cmd
4833 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
4834     if (!hci_can_send_command_packet_now()){
4835         log_error("hci_send_cmd called but cannot send packet now");
4836         return 0;
4837     }
4838 
4839     // for HCI INITIALIZATION
4840     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
4841     hci_stack->last_cmd_opcode = cmd->opcode;
4842 
4843     hci_reserve_packet_buffer();
4844     uint8_t * packet = hci_stack->hci_packet_buffer;
4845     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
4846     int err = hci_send_cmd_packet(packet, size);
4847 
4848     // release packet buffer on error or for synchronous transport implementations
4849     if ((err < 0) || hci_transport_synchronous()){
4850         hci_release_packet_buffer();
4851         hci_emit_transport_packet_sent();
4852     }
4853 
4854     return err;
4855 }
4856 
4857 /**
4858  * pre: numcmds >= 0 - it's allowed to send a command to the controller
4859  */
4860 int hci_send_cmd(const hci_cmd_t *cmd, ...){
4861     va_list argptr;
4862     va_start(argptr, cmd);
4863     int res = hci_send_cmd_va_arg(cmd, argptr);
4864     va_end(argptr);
4865     return res;
4866 }
4867 
4868 // Create various non-HCI events.
4869 // TODO: generalize, use table similar to hci_create_command
4870 
4871 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
4872     // dump packet
4873     if (dump) {
4874         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
4875     }
4876 
4877     // dispatch to all event handlers
4878     btstack_linked_list_iterator_t it;
4879     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
4880     while (btstack_linked_list_iterator_has_next(&it)){
4881         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
4882         entry->callback(HCI_EVENT_PACKET, 0, event, size);
4883     }
4884 }
4885 
4886 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
4887     if (!hci_stack->acl_packet_handler) return;
4888     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
4889 }
4890 
4891 #ifdef ENABLE_CLASSIC
4892 static void hci_notify_if_sco_can_send_now(void){
4893     // notify SCO sender if waiting
4894     if (!hci_stack->sco_waiting_for_can_send_now) return;
4895     if (hci_can_send_sco_packet_now()){
4896         hci_stack->sco_waiting_for_can_send_now = 0;
4897         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
4898         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
4899         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
4900     }
4901 }
4902 
4903 // parsing end emitting has been merged to reduce code size
4904 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
4905     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
4906 
4907     uint8_t * eir_data;
4908     ad_context_t context;
4909     const uint8_t * name;
4910     uint8_t         name_len;
4911 
4912     if (size < 3) return;
4913 
4914     int event_type = hci_event_packet_get_type(packet);
4915     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
4916     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
4917 
4918     switch (event_type){
4919         case HCI_EVENT_INQUIRY_RESULT:
4920         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4921             if (size != (3 + (num_responses * 14))) return;
4922             break;
4923         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4924             if (size != 257) return;
4925             if (num_responses != 1) return;
4926             break;
4927         default:
4928             return;
4929     }
4930 
4931     // event[1] is set at the end
4932     int i;
4933     for (i=0; i<num_responses;i++){
4934         memset(event, 0, sizeof(event));
4935         event[0] = GAP_EVENT_INQUIRY_RESULT;
4936         uint8_t event_size = 18;    // if name is not set by EIR
4937 
4938         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
4939         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
4940         (void)memcpy(&event[9],
4941                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
4942                      3); // class of device
4943         (void)memcpy(&event[12],
4944                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
4945                      2); // clock offset
4946 
4947         switch (event_type){
4948             case HCI_EVENT_INQUIRY_RESULT:
4949                 // 14,15,16,17 = 0, size 18
4950                 break;
4951             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4952                 event[14] = 1;
4953                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
4954                 // 16,17 = 0, size 18
4955                 break;
4956             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4957                 event[14] = 1;
4958                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
4959                 // EIR packets only contain a single inquiry response
4960                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
4961                 name = NULL;
4962                 // Iterate over EIR data
4963                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
4964                     uint8_t data_type    = ad_iterator_get_data_type(&context);
4965                     uint8_t data_size    = ad_iterator_get_data_len(&context);
4966                     const uint8_t * data = ad_iterator_get_data(&context);
4967                     // Prefer Complete Local Name over Shortend Local Name
4968                     switch (data_type){
4969                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
4970                             if (name) continue;
4971                             /* fall through */
4972                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
4973                             name = data;
4974                             name_len = data_size;
4975                             break;
4976                         default:
4977                             break;
4978                     }
4979                 }
4980                 if (name){
4981                     event[16] = 1;
4982                     // truncate name if needed
4983                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
4984                     event[17] = len;
4985                     (void)memcpy(&event[18], name, len);
4986                     event_size += len;
4987                 }
4988                 break;
4989             default:
4990                 return;
4991         }
4992         event[1] = event_size - 2;
4993         hci_emit_event(event, event_size, 1);
4994     }
4995 }
4996 #endif
4997 
4998 void hci_emit_state(void){
4999     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5000     uint8_t event[3];
5001     event[0] = BTSTACK_EVENT_STATE;
5002     event[1] = sizeof(event) - 2u;
5003     event[2] = hci_stack->state;
5004     hci_emit_event(event, sizeof(event), 1);
5005 }
5006 
5007 #ifdef ENABLE_CLASSIC
5008 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5009     uint8_t event[13];
5010     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5011     event[1] = sizeof(event) - 2;
5012     event[2] = status;
5013     little_endian_store_16(event, 3, con_handle);
5014     reverse_bd_addr(address, &event[5]);
5015     event[11] = 1; // ACL connection
5016     event[12] = 0; // encryption disabled
5017     hci_emit_event(event, sizeof(event), 1);
5018 }
5019 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
5020     if (disable_l2cap_timeouts) return;
5021     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
5022     uint8_t event[4];
5023     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
5024     event[1] = sizeof(event) - 2;
5025     little_endian_store_16(event, 2, conn->con_handle);
5026     hci_emit_event(event, sizeof(event), 1);
5027 }
5028 #endif
5029 
5030 #ifdef ENABLE_BLE
5031 #ifdef ENABLE_LE_CENTRAL
5032 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){
5033     uint8_t event[21];
5034     event[0] = HCI_EVENT_LE_META;
5035     event[1] = sizeof(event) - 2u;
5036     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
5037     event[3] = status;
5038     little_endian_store_16(event, 4, con_handle);
5039     event[6] = 0; // TODO: role
5040     event[7] = address_type;
5041     reverse_bd_addr(address, &event[8]);
5042     little_endian_store_16(event, 14, 0); // interval
5043     little_endian_store_16(event, 16, 0); // latency
5044     little_endian_store_16(event, 18, 0); // supervision timeout
5045     event[20] = 0; // master clock accuracy
5046     hci_emit_event(event, sizeof(event), 1);
5047 }
5048 #endif
5049 #endif
5050 
5051 static void hci_emit_transport_packet_sent(void){
5052     // notify upper stack that it might be possible to send again
5053     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5054     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5055 }
5056 
5057 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5058     uint8_t event[6];
5059     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
5060     event[1] = sizeof(event) - 2u;
5061     event[2] = 0; // status = OK
5062     little_endian_store_16(event, 3, con_handle);
5063     event[5] = reason;
5064     hci_emit_event(event, sizeof(event), 1);
5065 }
5066 
5067 static void hci_emit_nr_connections_changed(void){
5068     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5069     uint8_t event[3];
5070     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
5071     event[1] = sizeof(event) - 2u;
5072     event[2] = nr_hci_connections();
5073     hci_emit_event(event, sizeof(event), 1);
5074 }
5075 
5076 static void hci_emit_hci_open_failed(void){
5077     log_info("BTSTACK_EVENT_POWERON_FAILED");
5078     uint8_t event[2];
5079     event[0] = BTSTACK_EVENT_POWERON_FAILED;
5080     event[1] = sizeof(event) - 2u;
5081     hci_emit_event(event, sizeof(event), 1);
5082 }
5083 
5084 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
5085     log_info("hci_emit_dedicated_bonding_result %u ", status);
5086     uint8_t event[9];
5087     int pos = 0;
5088     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
5089     event[pos++] = sizeof(event) - 2u;
5090     event[pos++] = status;
5091     reverse_bd_addr(address, &event[pos]);
5092     hci_emit_event(event, sizeof(event), 1);
5093 }
5094 
5095 
5096 #ifdef ENABLE_CLASSIC
5097 
5098 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5099     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5100     uint8_t event[5];
5101     int pos = 0;
5102     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5103     event[pos++] = sizeof(event) - 2;
5104     little_endian_store_16(event, 2, con_handle);
5105     pos += 2;
5106     event[pos++] = level;
5107     hci_emit_event(event, sizeof(event), 1);
5108 }
5109 
5110 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
5111     if (!connection) return LEVEL_0;
5112     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5113     if ((connection->authentication_flags & CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5114     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
5115     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5116     // LEVEL 4 always requires 128 bit encrytion key size
5117     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5118         security_level = LEVEL_3;
5119     }
5120     return security_level;
5121 }
5122 
5123 static void hci_emit_discoverable_enabled(uint8_t enabled){
5124     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
5125     uint8_t event[3];
5126     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
5127     event[1] = sizeof(event) - 2;
5128     event[2] = enabled;
5129     hci_emit_event(event, sizeof(event), 1);
5130 }
5131 
5132 // query if remote side supports eSCO
5133 int hci_remote_esco_supported(hci_con_handle_t con_handle){
5134     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5135     if (!connection) return 0;
5136     return (connection->remote_supported_features[0] & 1) != 0;
5137 }
5138 
5139 static bool hci_ssp_supported(hci_connection_t * connection){
5140     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
5141     return (connection->bonding_flags & mask) == mask;
5142 }
5143 
5144 // query if remote side supports SSP
5145 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
5146     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5147     if (!connection) return 0;
5148     return hci_ssp_supported(connection) ? 1 : 0;
5149 }
5150 
5151 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5152     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5153 }
5154 
5155 // GAP API
5156 /**
5157  * @bbrief enable/disable bonding. default is enabled
5158  * @praram enabled
5159  */
5160 void gap_set_bondable_mode(int enable){
5161     hci_stack->bondable = enable ? 1 : 0;
5162 }
5163 /**
5164  * @brief Get bondable mode.
5165  * @return 1 if bondable
5166  */
5167 int gap_get_bondable_mode(void){
5168     return hci_stack->bondable;
5169 }
5170 
5171 /**
5172  * @brief map link keys to security levels
5173  */
5174 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
5175     switch (link_key_type){
5176         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5177             return LEVEL_4;
5178         case COMBINATION_KEY:
5179         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5180             return LEVEL_3;
5181         default:
5182             return LEVEL_2;
5183     }
5184 }
5185 
5186 /**
5187  * @brief map link keys to secure connection yes/no
5188  */
5189 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
5190     switch (link_key_type){
5191         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5192         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5193             return 1;
5194         default:
5195             return 0;
5196     }
5197 }
5198 
5199 /**
5200  * @brief map link keys to authenticated
5201  */
5202 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
5203     switch (link_key_type){
5204         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5205         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5206             return 1;
5207         default:
5208             return 0;
5209     }
5210 }
5211 
5212 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
5213     log_info("gap_mitm_protection_required_for_security_level %u", level);
5214     return level > LEVEL_2;
5215 }
5216 
5217 /**
5218  * @brief get current security level
5219  */
5220 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
5221     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5222     if (!connection) return LEVEL_0;
5223     return gap_security_level_for_connection(connection);
5224 }
5225 
5226 /**
5227  * @brief request connection to device to
5228  * @result GAP_AUTHENTICATION_RESULT
5229  */
5230 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
5231     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5232     if (!connection){
5233         hci_emit_security_level(con_handle, LEVEL_0);
5234         return;
5235     }
5236 
5237     btstack_assert(hci_is_le_connection(connection) == false);
5238 
5239     gap_security_level_t current_level = gap_security_level(con_handle);
5240     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
5241         requested_level, connection->requested_security_level, current_level);
5242 
5243     // assumption: earlier requested security higher than current level => security request is active
5244     if (current_level < connection->requested_security_level){
5245         if (connection->requested_security_level < requested_level){
5246             // increase requested level as new level is higher
5247 
5248             // TODO: handle re-authentication when done
5249 
5250             connection->requested_security_level = requested_level;
5251         }
5252         return;
5253     }
5254 
5255     // no request active, notify if security sufficient
5256     if (requested_level <= current_level){
5257         hci_emit_security_level(con_handle, current_level);
5258         return;
5259     }
5260 
5261     // store request
5262     connection->requested_security_level = requested_level;
5263 
5264     // start to authenticate connection if authentication not already active
5265     if ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
5266     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5267     hci_run();
5268 }
5269 
5270 /**
5271  * @brief start dedicated bonding with device. disconnect after bonding
5272  * @param device
5273  * @param request MITM protection
5274  * @result GAP_DEDICATED_BONDING_COMPLETE
5275  */
5276 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5277 
5278     // create connection state machine
5279     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5280 
5281     if (!connection){
5282         return BTSTACK_MEMORY_ALLOC_FAILED;
5283     }
5284 
5285     // delete linkn key
5286     gap_drop_link_key_for_bd_addr(device);
5287 
5288     // configure LEVEL_2/3, dedicated bonding
5289     connection->state = SEND_CREATE_CONNECTION;
5290     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5291     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5292     connection->bonding_flags = BONDING_DEDICATED;
5293 
5294     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5295 
5296     // handle: connnection failure (connection complete != ok)
5297     // handle: authentication failure
5298     // handle: disconnect on done
5299 
5300     hci_run();
5301 
5302     return 0;
5303 }
5304 #endif
5305 
5306 void gap_set_local_name(const char * local_name){
5307     hci_stack->local_name = local_name;
5308 }
5309 
5310 
5311 #ifdef ENABLE_BLE
5312 
5313 #ifdef ENABLE_LE_CENTRAL
5314 void gap_start_scan(void){
5315     hci_stack->le_scanning_enabled = true;
5316     hci_run();
5317 }
5318 
5319 void gap_stop_scan(void){
5320     hci_stack->le_scanning_enabled = false;
5321     hci_run();
5322 }
5323 
5324 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5325     hci_stack->le_scan_type          = scan_type;
5326     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5327     hci_stack->le_scan_interval      = scan_interval;
5328     hci_stack->le_scan_window        = scan_window;
5329     hci_stack->le_scanning_param_update = true;
5330     hci_run();
5331 }
5332 
5333 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5334     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5335 }
5336 
5337 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
5338     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
5339     if (!conn){
5340         // disallow if le connection is already outgoing
5341         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5342             log_error("le connection already active");
5343             return ERROR_CODE_COMMAND_DISALLOWED;
5344         }
5345 
5346         log_info("gap_connect: no connection exists yet, creating context");
5347         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
5348         if (!conn){
5349             // notify client that alloc failed
5350             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5351             log_info("gap_connect: failed to alloc hci_connection_t");
5352             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
5353         }
5354 
5355         // set le connecting state
5356         if (hci_is_le_connection_type(addr_type)){
5357             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5358         }
5359 
5360         conn->state = SEND_CREATE_CONNECTION;
5361         log_info("gap_connect: send create connection next");
5362         hci_run();
5363         return ERROR_CODE_SUCCESS;
5364     }
5365 
5366     if (!hci_is_le_connection(conn) ||
5367         (conn->state == SEND_CREATE_CONNECTION) ||
5368         (conn->state == SENT_CREATE_CONNECTION)) {
5369         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5370         log_error("gap_connect: classic connection or connect is already being created");
5371         return GATT_CLIENT_IN_WRONG_STATE;
5372     }
5373 
5374     // check if connection was just disconnected
5375     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5376         log_info("gap_connect: send create connection (again)");
5377         conn->state = SEND_CREATE_CONNECTION;
5378         hci_run();
5379         return ERROR_CODE_SUCCESS;
5380     }
5381 
5382     log_info("gap_connect: context exists with state %u", conn->state);
5383     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
5384     hci_run();
5385     return ERROR_CODE_SUCCESS;
5386 }
5387 
5388 // @assumption: only a single outgoing LE Connection exists
5389 static hci_connection_t * gap_get_outgoing_connection(void){
5390     btstack_linked_item_t *it;
5391     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5392         hci_connection_t * conn = (hci_connection_t *) it;
5393         if (!hci_is_le_connection(conn)) continue;
5394         switch (conn->state){
5395             case SEND_CREATE_CONNECTION:
5396             case SENT_CREATE_CONNECTION:
5397             case SENT_CANCEL_CONNECTION:
5398                 return conn;
5399             default:
5400                 break;
5401         };
5402     }
5403     return NULL;
5404 }
5405 
5406 uint8_t gap_connect_cancel(void){
5407     hci_connection_t * conn = gap_get_outgoing_connection();
5408     if (!conn) return 0;
5409     switch (conn->state){
5410         case SEND_CREATE_CONNECTION:
5411             // skip sending create connection and emit event instead
5412             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5413             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
5414             btstack_memory_hci_connection_free( conn );
5415             break;
5416         case SENT_CREATE_CONNECTION:
5417             // request to send cancel connection
5418             conn->state = SEND_CANCEL_CONNECTION;
5419             hci_run();
5420             break;
5421         default:
5422             break;
5423     }
5424     return 0;
5425 }
5426 #endif
5427 
5428 #ifdef ENABLE_LE_CENTRAL
5429 /**
5430  * @brief Set connection parameters for outgoing connections
5431  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5432  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
5433  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
5434  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
5435  * @param conn_latency, default: 4
5436  * @param supervision_timeout (unit: 10ms), default: 720 ms
5437  * @param min_ce_length (unit: 0.625ms), default: 10 ms
5438  * @param max_ce_length (unit: 0.625ms), default: 30 ms
5439  */
5440 
5441 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5442     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5443     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5444     hci_stack->le_connection_scan_interval = conn_scan_interval;
5445     hci_stack->le_connection_scan_window = conn_scan_window;
5446     hci_stack->le_connection_interval_min = conn_interval_min;
5447     hci_stack->le_connection_interval_max = conn_interval_max;
5448     hci_stack->le_connection_latency = conn_latency;
5449     hci_stack->le_supervision_timeout = supervision_timeout;
5450     hci_stack->le_minimum_ce_length = min_ce_length;
5451     hci_stack->le_maximum_ce_length = max_ce_length;
5452 }
5453 #endif
5454 
5455 /**
5456  * @brief Updates the connection parameters for a given LE connection
5457  * @param handle
5458  * @param conn_interval_min (unit: 1.25ms)
5459  * @param conn_interval_max (unit: 1.25ms)
5460  * @param conn_latency
5461  * @param supervision_timeout (unit: 10ms)
5462  * @returns 0 if ok
5463  */
5464 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5465     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5466     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5467     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5468     connection->le_conn_interval_min = conn_interval_min;
5469     connection->le_conn_interval_max = conn_interval_max;
5470     connection->le_conn_latency = conn_latency;
5471     connection->le_supervision_timeout = supervision_timeout;
5472     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
5473     hci_run();
5474     return 0;
5475 }
5476 
5477 /**
5478  * @brief Request an update of the connection parameter for a given LE connection
5479  * @param handle
5480  * @param conn_interval_min (unit: 1.25ms)
5481  * @param conn_interval_max (unit: 1.25ms)
5482  * @param conn_latency
5483  * @param supervision_timeout (unit: 10ms)
5484  * @returns 0 if ok
5485  */
5486 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5487     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5488     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5489     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5490     connection->le_conn_interval_min = conn_interval_min;
5491     connection->le_conn_interval_max = conn_interval_max;
5492     connection->le_conn_latency = conn_latency;
5493     connection->le_supervision_timeout = supervision_timeout;
5494     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
5495     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
5496     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
5497     return 0;
5498 }
5499 
5500 #ifdef ENABLE_LE_PERIPHERAL
5501 
5502 /**
5503  * @brief Set Advertisement Data
5504  * @param advertising_data_length
5505  * @param advertising_data (max 31 octets)
5506  * @note data is not copied, pointer has to stay valid
5507  */
5508 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
5509     hci_stack->le_advertisements_data_len = advertising_data_length;
5510     hci_stack->le_advertisements_data = advertising_data;
5511     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5512     hci_run();
5513 }
5514 
5515 /**
5516  * @brief Set Scan Response Data
5517  * @param advertising_data_length
5518  * @param advertising_data (max 31 octets)
5519  * @note data is not copied, pointer has to stay valid
5520  */
5521 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
5522     hci_stack->le_scan_response_data_len = scan_response_data_length;
5523     hci_stack->le_scan_response_data = scan_response_data;
5524     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5525     hci_run();
5526 }
5527 
5528 /**
5529  * @brief Set Advertisement Parameters
5530  * @param adv_int_min
5531  * @param adv_int_max
5532  * @param adv_type
5533  * @param direct_address_type
5534  * @param direct_address
5535  * @param channel_map
5536  * @param filter_policy
5537  *
5538  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
5539  */
5540  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
5541     uint8_t direct_address_typ, bd_addr_t direct_address,
5542     uint8_t channel_map, uint8_t filter_policy) {
5543 
5544     hci_stack->le_advertisements_interval_min = adv_int_min;
5545     hci_stack->le_advertisements_interval_max = adv_int_max;
5546     hci_stack->le_advertisements_type = adv_type;
5547     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
5548     hci_stack->le_advertisements_channel_map = channel_map;
5549     hci_stack->le_advertisements_filter_policy = filter_policy;
5550     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
5551                  6);
5552 
5553     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5554     hci_run();
5555  }
5556 
5557 /**
5558  * @brief Enable/Disable Advertisements
5559  * @param enabled
5560  */
5561 void gap_advertisements_enable(int enabled){
5562     hci_stack->le_advertisements_enabled = enabled != 0;
5563     hci_update_advertisements_enabled_for_current_roles();
5564     hci_run();
5565 }
5566 
5567 #endif
5568 
5569 void hci_le_set_own_address_type(uint8_t own_address_type){
5570     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
5571     if (own_address_type == hci_stack->le_own_addr_type) return;
5572     hci_stack->le_own_addr_type = own_address_type;
5573 
5574 #ifdef ENABLE_LE_PERIPHERAL
5575     // update advertisement parameters, too
5576     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5577     hci_run();
5578 #endif
5579 #ifdef ENABLE_LE_CENTRAL
5580     // note: we don't update scan parameters or modify ongoing connection attempts
5581 #endif
5582 }
5583 
5584 #endif
5585 
5586 uint8_t gap_disconnect(hci_con_handle_t handle){
5587     hci_connection_t * conn = hci_connection_for_handle(handle);
5588     if (!conn){
5589         hci_emit_disconnection_complete(handle, 0);
5590         return 0;
5591     }
5592     // ignore if already disconnected
5593     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5594         return 0;
5595     }
5596     conn->state = SEND_DISCONNECT;
5597     hci_run();
5598     return 0;
5599 }
5600 
5601 int gap_read_rssi(hci_con_handle_t con_handle){
5602     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5603     if (hci_connection == NULL) return 0;
5604     connectionSetAuthenticationFlags(hci_connection, READ_RSSI);
5605     hci_run();
5606     return 1;
5607 }
5608 
5609 /**
5610  * @brief Get connection type
5611  * @param con_handle
5612  * @result connection_type
5613  */
5614 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
5615     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5616     if (!conn) return GAP_CONNECTION_INVALID;
5617     switch (conn->address_type){
5618         case BD_ADDR_TYPE_LE_PUBLIC:
5619         case BD_ADDR_TYPE_LE_RANDOM:
5620             return GAP_CONNECTION_LE;
5621         case BD_ADDR_TYPE_SCO:
5622             return GAP_CONNECTION_SCO;
5623         case BD_ADDR_TYPE_ACL:
5624             return GAP_CONNECTION_ACL;
5625         default:
5626             return GAP_CONNECTION_INVALID;
5627     }
5628 }
5629 
5630 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
5631     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5632     if (!conn) return HCI_ROLE_INVALID;
5633     return (hci_role_t) conn->role;
5634 }
5635 
5636 
5637 #ifdef ENABLE_CLASSIC
5638 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
5639     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5640     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5641     conn->request_role = role;
5642     hci_run();
5643     return ERROR_CODE_SUCCESS;
5644 }
5645 #endif
5646 
5647 #ifdef ENABLE_BLE
5648 
5649 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){
5650     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5651     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5652 
5653     conn->le_phy_update_all_phys    = all_phys;
5654     conn->le_phy_update_tx_phys     = tx_phys;
5655     conn->le_phy_update_rx_phys     = rx_phys;
5656     conn->le_phy_update_phy_options = phy_options;
5657 
5658     hci_run();
5659 
5660     return 0;
5661 }
5662 
5663 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
5664     // check if already in list
5665     btstack_linked_list_iterator_t it;
5666     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5667     while (btstack_linked_list_iterator_has_next(&it)) {
5668         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
5669         if (entry->address_type != address_type) {
5670             continue;
5671         }
5672         if (memcmp(entry->address, address, 6) != 0) {
5673             continue;
5674         }
5675 		// disallow if already scheduled to add
5676 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
5677 			return ERROR_CODE_COMMAND_DISALLOWED;
5678 		}
5679 		// still on controller, but scheduled to remove -> re-add
5680 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
5681 		return ERROR_CODE_SUCCESS;
5682     }
5683     // alloc and add to list
5684     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
5685     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
5686     entry->address_type = address_type;
5687     (void)memcpy(entry->address, address, 6);
5688     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5689     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
5690     return ERROR_CODE_SUCCESS;
5691 }
5692 
5693 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
5694     btstack_linked_list_iterator_t it;
5695     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5696     while (btstack_linked_list_iterator_has_next(&it)){
5697         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5698         if (entry->address_type != address_type) {
5699             continue;
5700         }
5701         if (memcmp(entry->address, address, 6) != 0) {
5702             continue;
5703         }
5704         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5705             // remove from controller if already present
5706             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5707         }  else {
5708             // directly remove entry from whitelist
5709             btstack_linked_list_iterator_remove(&it);
5710             btstack_memory_whitelist_entry_free(entry);
5711         }
5712         return ERROR_CODE_SUCCESS;
5713     }
5714     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5715 }
5716 
5717 static void hci_whitelist_clear(void){
5718     btstack_linked_list_iterator_t it;
5719     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5720     while (btstack_linked_list_iterator_has_next(&it)){
5721         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5722         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5723             // remove from controller if already present
5724             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5725             continue;
5726         }
5727         // directly remove entry from whitelist
5728         btstack_linked_list_iterator_remove(&it);
5729         btstack_memory_whitelist_entry_free(entry);
5730     }
5731 }
5732 
5733 /**
5734  * @brief Clear Whitelist
5735  * @returns 0 if ok
5736  */
5737 uint8_t gap_whitelist_clear(void){
5738     hci_whitelist_clear();
5739     hci_run();
5740     return ERROR_CODE_SUCCESS;
5741 }
5742 
5743 /**
5744  * @brief Add Device to Whitelist
5745  * @param address_typ
5746  * @param address
5747  * @returns 0 if ok
5748  */
5749 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
5750     uint8_t status = hci_whitelist_add(address_type, address);
5751     if (status){
5752         return status;
5753     }
5754     hci_run();
5755     return ERROR_CODE_SUCCESS;
5756 }
5757 
5758 /**
5759  * @brief Remove Device from Whitelist
5760  * @param address_typ
5761  * @param address
5762  * @returns 0 if ok
5763  */
5764 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
5765     uint8_t status = hci_whitelist_remove(address_type, address);
5766     if (status){
5767         return status;
5768     }
5769     hci_run();
5770     return ERROR_CODE_SUCCESS;
5771 }
5772 
5773 #ifdef ENABLE_LE_CENTRAL
5774 /**
5775  *  @brief Connect with Whitelist
5776  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
5777  *  @returns - if ok
5778  */
5779 uint8_t gap_connect_with_whitelist(void){
5780     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5781         return ERROR_CODE_COMMAND_DISALLOWED;
5782     }
5783     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
5784     hci_run();
5785     return ERROR_CODE_SUCCESS;
5786 }
5787 
5788 /**
5789  * @brief Auto Connection Establishment - Start Connecting to device
5790  * @param address_typ
5791  * @param address
5792  * @returns 0 if ok
5793  */
5794 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
5795     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
5796         return ERROR_CODE_COMMAND_DISALLOWED;
5797     }
5798 
5799     uint8_t status = hci_whitelist_add(address_type, address);
5800     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
5801         return status;
5802     }
5803 
5804     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
5805 
5806     hci_run();
5807     return ERROR_CODE_SUCCESS;
5808 }
5809 
5810 /**
5811  * @brief Auto Connection Establishment - Stop Connecting to device
5812  * @param address_typ
5813  * @param address
5814  * @returns 0 if ok
5815  */
5816 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
5817     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
5818         return ERROR_CODE_COMMAND_DISALLOWED;
5819     }
5820 
5821     hci_whitelist_remove(address_type, address);
5822     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
5823         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5824     }
5825     hci_run();
5826     return 0;
5827 }
5828 
5829 /**
5830  * @brief Auto Connection Establishment - Stop everything
5831  * @note  Convenience function to stop all active auto connection attempts
5832  */
5833 uint8_t gap_auto_connection_stop_all(void){
5834     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
5835         return ERROR_CODE_COMMAND_DISALLOWED;
5836     }
5837     hci_whitelist_clear();
5838     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5839     hci_run();
5840     return ERROR_CODE_SUCCESS;
5841 }
5842 
5843 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
5844     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5845     if (!conn) return 0;
5846     return conn->le_connection_interval;
5847 }
5848 #endif
5849 #endif
5850 
5851 #ifdef ENABLE_CLASSIC
5852 /**
5853  * @brief Set Extended Inquiry Response data
5854  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
5855  * @note has to be done before stack starts up
5856  */
5857 void gap_set_extended_inquiry_response(const uint8_t * data){
5858     hci_stack->eir_data = data;
5859 }
5860 
5861 /**
5862  * @brief Start GAP Classic Inquiry
5863  * @param duration in 1.28s units
5864  * @return 0 if ok
5865  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
5866  */
5867 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
5868     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
5869     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5870     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
5871         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
5872     }
5873     hci_stack->inquiry_state = duration_in_1280ms_units;
5874     hci_run();
5875     return 0;
5876 }
5877 
5878 /**
5879  * @brief Stop GAP Classic Inquiry
5880  * @returns 0 if ok
5881  */
5882 int gap_inquiry_stop(void){
5883     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
5884         // emit inquiry complete event, before it even started
5885         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
5886         hci_emit_event(event, sizeof(event), 1);
5887         return 0;
5888     }
5889     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
5890     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
5891     hci_run();
5892     return 0;
5893 }
5894 
5895 
5896 /**
5897  * @brief Remote Name Request
5898  * @param addr
5899  * @param page_scan_repetition_mode
5900  * @param clock_offset only used when bit 15 is set
5901  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
5902  */
5903 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
5904     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5905     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
5906     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
5907     hci_stack->remote_name_clock_offset = clock_offset;
5908     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
5909     hci_run();
5910     return 0;
5911 }
5912 
5913 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
5914     hci_stack->gap_pairing_state = state;
5915     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
5916     hci_run();
5917     return 0;
5918 }
5919 
5920 /**
5921  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
5922  * @param addr
5923  * @param pin_data
5924  * @param pin_len
5925  * @return 0 if ok
5926  */
5927 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
5928     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5929     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
5930     hci_stack->gap_pairing_pin_len = pin_len;
5931     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
5932 }
5933 
5934 /**
5935  * @brief Legacy Pairing Pin Code Response
5936  * @param addr
5937  * @param pin
5938  * @return 0 if ok
5939  */
5940 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
5941     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
5942 }
5943 
5944 /**
5945  * @brief Abort Legacy Pairing
5946  * @param addr
5947  * @param pin
5948  * @return 0 if ok
5949  */
5950 int gap_pin_code_negative(bd_addr_t addr){
5951     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5952     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
5953 }
5954 
5955 /**
5956  * @brief SSP Passkey Response
5957  * @param addr
5958  * @param passkey
5959  * @return 0 if ok
5960  */
5961 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
5962     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5963     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
5964     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
5965 }
5966 
5967 /**
5968  * @brief Abort SSP Passkey Entry/Pairing
5969  * @param addr
5970  * @param pin
5971  * @return 0 if ok
5972  */
5973 int gap_ssp_passkey_negative(const bd_addr_t addr){
5974     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5975     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
5976 }
5977 
5978 /**
5979  * @brief Accept SSP Numeric Comparison
5980  * @param addr
5981  * @param passkey
5982  * @return 0 if ok
5983  */
5984 int gap_ssp_confirmation_response(const bd_addr_t addr){
5985     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5986     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
5987 }
5988 
5989 /**
5990  * @brief Abort SSP Numeric Comparison/Pairing
5991  * @param addr
5992  * @param pin
5993  * @return 0 if ok
5994  */
5995 int gap_ssp_confirmation_negative(const bd_addr_t addr){
5996     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5997     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
5998 }
5999 
6000 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
6001 
6002 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
6003     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6004     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6005     connectionSetAuthenticationFlags(conn, flag);
6006     hci_run();
6007     return ERROR_CODE_SUCCESS;
6008 }
6009 
6010 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
6011     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_REPLY);
6012 }
6013 
6014 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
6015     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6016 }
6017 #endif
6018 
6019 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6020 /**
6021  * @brief Report Remote OOB Data
6022  * @param bd_addr
6023  * @param c_192 Simple Pairing Hash C derived from P-192 public key
6024  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
6025  * @param c_256 Simple Pairing Hash C derived from P-256 public key
6026  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
6027  */
6028 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){
6029     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6030     if (connection == NULL) {
6031         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6032     }
6033     connection->classic_oob_c_192 = c_192;
6034     connection->classic_oob_r_192 = r_192;
6035     connection->classic_oob_c_256 = c_256;
6036     connection->classic_oob_r_256 = r_256;
6037     return ERROR_CODE_SUCCESS;
6038 }
6039 /**
6040  * @brief Generate new OOB data
6041  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6042  */
6043 void gap_ssp_generate_oob_data(void){
6044     hci_stack->classic_read_local_oob_data = true;
6045     hci_run();
6046 }
6047 
6048 #endif
6049 
6050 /**
6051  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6052  * @param inquiry_mode see bluetooth_defines.h
6053  */
6054 void hci_set_inquiry_mode(inquiry_mode_t mode){
6055     hci_stack->inquiry_mode = mode;
6056 }
6057 
6058 /**
6059  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6060  */
6061 void hci_set_sco_voice_setting(uint16_t voice_setting){
6062     hci_stack->sco_voice_setting = voice_setting;
6063 }
6064 
6065 /**
6066  * @brief Get SCO Voice Setting
6067  * @return current voice setting
6068  */
6069 uint16_t hci_get_sco_voice_setting(void){
6070     return hci_stack->sco_voice_setting;
6071 }
6072 
6073 static int hci_have_usb_transport(void){
6074     if (!hci_stack->hci_transport) return 0;
6075     const char * transport_name = hci_stack->hci_transport->name;
6076     if (!transport_name) return 0;
6077     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6078 }
6079 
6080 /** @brief Get SCO packet length for current SCO Voice setting
6081  *  @note  Using SCO packets of the exact length is required for USB transfer
6082  *  @return Length of SCO packets in bytes (not audio frames)
6083  */
6084 int hci_get_sco_packet_length(void){
6085     int sco_packet_length = 0;
6086     int multiplier;
6087 #ifdef ENABLE_SCO_OVER_HCI
6088 
6089     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6090     multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6091 
6092     if (hci_have_usb_transport()){
6093         // see Core Spec for H2 USB Transfer.
6094         // 3 byte SCO header + 24 bytes per connection
6095         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
6096         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6097     } else {
6098         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6099         sco_packet_length = 3 + 60 * multiplier;
6100         // assert that it still fits inside an SCO buffer
6101         if (sco_packet_length > hci_stack->sco_data_packet_length){
6102             sco_packet_length = 3 + 60;
6103         }
6104     }
6105 #endif
6106 
6107 #ifdef HAVE_SCO_TRANSPORT
6108     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6109     multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6110     sco_packet_length = 3 + 60 * multiplier;
6111 #endif
6112 
6113     return sco_packet_length;
6114 }
6115 
6116 /**
6117 * @brief Sets the master/slave policy
6118 * @param policy (0: attempt to become master, 1: let connecting device decide)
6119 */
6120 void hci_set_master_slave_policy(uint8_t policy){
6121     hci_stack->master_slave_policy = policy;
6122 }
6123 
6124 #endif
6125 
6126 HCI_STATE hci_get_state(void){
6127     return hci_stack->state;
6128 }
6129 
6130 #ifdef ENABLE_CLASSIC
6131 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
6132     hci_stack->gap_classic_accept_callback = accept_callback;
6133 }
6134 #endif
6135 
6136 /**
6137  * @brief Set callback for Bluetooth Hardware Error
6138  */
6139 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6140     hci_stack->hardware_error_callback = fn;
6141 }
6142 
6143 void hci_disconnect_all(void){
6144     btstack_linked_list_iterator_t it;
6145     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6146     while (btstack_linked_list_iterator_has_next(&it)){
6147         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6148         if (con->state == SENT_DISCONNECT) continue;
6149         con->state = SEND_DISCONNECT;
6150     }
6151     hci_run();
6152 }
6153 
6154 uint16_t hci_get_manufacturer(void){
6155     return hci_stack->manufacturer;
6156 }
6157 
6158 #ifdef ENABLE_BLE
6159 
6160 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
6161     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
6162     if (!hci_con) return NULL;
6163     return &hci_con->sm_connection;
6164 }
6165 
6166 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
6167 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
6168 
6169 int gap_encryption_key_size(hci_con_handle_t con_handle){
6170     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6171     if (hci_connection == NULL) return 0;
6172     if (hci_is_le_connection(hci_connection)){
6173         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6174         if (sm_conn->sm_connection_encrypted) {
6175             return sm_conn->sm_actual_encryption_key_size;
6176         }
6177     }
6178 #ifdef ENABLE_CLASSIC
6179     else {
6180         if ((hci_connection->authentication_flags & CONNECTION_ENCRYPTED)){
6181             return hci_connection->encryption_key_size;
6182         }
6183     }
6184 #endif
6185     return 0;
6186 }
6187 
6188 int gap_authenticated(hci_con_handle_t con_handle){
6189     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6190     if (hci_connection == NULL) return 0;
6191 
6192     switch (hci_connection->address_type){
6193         case BD_ADDR_TYPE_LE_PUBLIC:
6194         case BD_ADDR_TYPE_LE_RANDOM:
6195             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6196             return hci_connection->sm_connection.sm_connection_authenticated;
6197 #ifdef ENABLE_CLASSIC
6198         case BD_ADDR_TYPE_SCO:
6199         case BD_ADDR_TYPE_ACL:
6200             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
6201 #endif
6202         default:
6203             return 0;
6204     }
6205 }
6206 
6207 int gap_secure_connection(hci_con_handle_t con_handle){
6208     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6209     if (hci_connection == NULL) return 0;
6210 
6211     switch (hci_connection->address_type){
6212         case BD_ADDR_TYPE_LE_PUBLIC:
6213         case BD_ADDR_TYPE_LE_RANDOM:
6214             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6215             return hci_connection->sm_connection.sm_connection_sc;
6216 #ifdef ENABLE_CLASSIC
6217         case BD_ADDR_TYPE_SCO:
6218         case BD_ADDR_TYPE_ACL:
6219             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
6220 #endif
6221         default:
6222             return 0;
6223     }
6224 }
6225 
6226 bool gap_bonded(hci_con_handle_t con_handle){
6227 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6228 	if (hci_connection == NULL) return 0;
6229 
6230 #ifdef ENABLE_CLASSIC
6231 	link_key_t link_key;
6232 	link_key_type_t link_key_type;
6233 #endif
6234 	switch (hci_connection->address_type){
6235 		case BD_ADDR_TYPE_LE_PUBLIC:
6236 		case BD_ADDR_TYPE_LE_RANDOM:
6237 			return hci_connection->sm_connection.sm_le_db_index >= 0;
6238 #ifdef ENABLE_CLASSIC
6239 		case BD_ADDR_TYPE_SCO:
6240 		case BD_ADDR_TYPE_ACL:
6241 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
6242 #endif
6243 		default:
6244 			return false;
6245 	}
6246 }
6247 
6248 
6249 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
6250     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
6251     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
6252     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
6253     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
6254     return sm_conn->sm_connection_authorization_state;
6255 }
6256 #endif
6257 
6258 #ifdef ENABLE_CLASSIC
6259 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){
6260     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6261     if (!conn) return GAP_CONNECTION_INVALID;
6262     conn->sniff_min_interval = sniff_min_interval;
6263     conn->sniff_max_interval = sniff_max_interval;
6264     conn->sniff_attempt = sniff_attempt;
6265     conn->sniff_timeout = sniff_timeout;
6266     hci_run();
6267     return 0;
6268 }
6269 
6270 /**
6271  * @brief Exit Sniff mode
6272  * @param con_handle
6273  @ @return 0 if ok
6274  */
6275 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6276     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6277     if (!conn) return GAP_CONNECTION_INVALID;
6278     conn->sniff_min_interval = 0xffff;
6279     hci_run();
6280     return 0;
6281 }
6282 #endif
6283 
6284 void hci_halting_defer(void){
6285     if (hci_stack->state != HCI_STATE_HALTING) return;
6286     switch (hci_stack->substate){
6287         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6288         case HCI_HALTING_CLOSE:
6289             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6290             break;
6291         default:
6292             break;
6293     }
6294 }
6295 
6296 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6297 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
6298     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6299     if (le_device_db_index >= le_device_db_max_count()) return;
6300     uint8_t offset = le_device_db_index >> 3;
6301     uint8_t mask = 1 << (le_device_db_index & 7);
6302     hci_stack->le_resolving_list_add_entries[offset] |= mask;
6303     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6304     	// note: go back to remove entries, otherwise, a remove + add will skip the add
6305         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6306     }
6307 }
6308 
6309 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
6310 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6311 	if (le_device_db_index >= le_device_db_max_count()) return;
6312 	uint8_t offset = le_device_db_index >> 3;
6313 	uint8_t mask = 1 << (le_device_db_index & 7);
6314 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
6315 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6316 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6317 	}
6318 }
6319 
6320 uint8_t gap_load_resolving_list_from_le_device_db(void){
6321 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6322 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6323 	}
6324 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6325 		// restart le resolving list update
6326 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6327 	}
6328 	return ERROR_CODE_SUCCESS;
6329 }
6330 #endif
6331 
6332 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
6333 void hci_setup_test_connections_fuzz(void){
6334     hci_connection_t * conn;
6335 
6336     // default address: 66:55:44:33:00:01
6337     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
6338 
6339     // setup Controller info
6340     hci_stack->num_cmd_packets = 255;
6341     hci_stack->acl_packets_total_num = 255;
6342 
6343     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
6344     addr[5] = 0x01;
6345     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6346     conn->con_handle = addr[5];
6347     conn->role  = HCI_ROLE_SLAVE;
6348     conn->state = RECEIVED_CONNECTION_REQUEST;
6349     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6350 
6351     // setup incoming Classic SCO connection with con handle 0x0002
6352     addr[5] = 0x02;
6353     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6354     conn->con_handle = addr[5];
6355     conn->role  = HCI_ROLE_SLAVE;
6356     conn->state = RECEIVED_CONNECTION_REQUEST;
6357     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6358 
6359     // setup ready Classic ACL connection with con handle 0x0003
6360     addr[5] = 0x03;
6361     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6362     conn->con_handle = addr[5];
6363     conn->role  = HCI_ROLE_SLAVE;
6364     conn->state = OPEN;
6365     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6366 
6367     // setup ready Classic SCO connection with con handle 0x0004
6368     addr[5] = 0x04;
6369     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6370     conn->con_handle = addr[5];
6371     conn->role  = HCI_ROLE_SLAVE;
6372     conn->state = OPEN;
6373     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6374 
6375     // setup ready LE ACL connection with con handle 0x005 and public address
6376     addr[5] = 0x05;
6377     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
6378     conn->con_handle = addr[5];
6379     conn->role  = HCI_ROLE_SLAVE;
6380     conn->state = OPEN;
6381     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6382 }
6383 
6384 void hci_free_connections_fuzz(void){
6385     btstack_linked_list_iterator_t it;
6386     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6387     while (btstack_linked_list_iterator_has_next(&it)){
6388         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6389         btstack_linked_list_iterator_remove(&it);
6390         btstack_memory_hci_connection_free(con);
6391     }
6392 }
6393 void hci_simulate_working_fuzz(void){
6394     hci_init_done();
6395     hci_stack->num_cmd_packets = 255;
6396 }
6397 #endif
6398