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