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