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