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