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