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