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