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