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