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