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