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