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