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