xref: /btstack/src/hci.c (revision 79e0fa07b4af264228714ff4798d45a4b1efc7f9)
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 #endif
2404 
2405 static void event_handler(uint8_t *packet, uint16_t size){
2406 
2407     uint16_t event_length = packet[1];
2408 
2409     // assert packet is complete
2410     if (size != (event_length + 2u)){
2411         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
2412         return;
2413     }
2414 
2415     bd_addr_type_t addr_type;
2416     hci_con_handle_t handle;
2417     hci_connection_t * conn;
2418     int i;
2419     int create_connection_cmd;
2420 
2421 #ifdef ENABLE_CLASSIC
2422     hci_link_type_t link_type;
2423     bd_addr_t addr;
2424 #endif
2425 
2426     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
2427 
2428     switch (hci_event_packet_get_type(packet)) {
2429 
2430         case HCI_EVENT_COMMAND_COMPLETE:
2431             handle_command_complete_event(packet, size);
2432             break;
2433 
2434         case HCI_EVENT_COMMAND_STATUS:
2435             // get num cmd packets - limit to 1 to reduce complexity
2436             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2437 
2438             // check command status to detected failed outgoing connections
2439             create_connection_cmd = 0;
2440 #ifdef ENABLE_CLASSIC
2441             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2442                 create_connection_cmd = 1;
2443             }
2444 #endif
2445 #ifdef ENABLE_LE_CENTRAL
2446             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
2447                 create_connection_cmd = 1;
2448             }
2449 #endif
2450             if (create_connection_cmd) {
2451                 uint8_t status = hci_event_command_status_get_status(packet);
2452                 addr_type = hci_stack->outgoing_addr_type;
2453                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
2454                 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);
2455 
2456                 // reset outgoing address info
2457                 memset(hci_stack->outgoing_addr, 0, 6);
2458                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2459 
2460                 // on error
2461                 if (status != ERROR_CODE_SUCCESS){
2462 #ifdef ENABLE_LE_CENTRAL
2463                     if (hci_is_le_connection_type(addr_type)){
2464                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2465                         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2466                     }
2467 #endif
2468                     // error => outgoing connection failed
2469                     if (conn != NULL){
2470                         hci_handle_connection_failed(conn, status);
2471                     }
2472                 }
2473             }
2474 
2475 #ifdef ENABLE_CLASSIC
2476             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_inquiry)) {
2477                 uint8_t status = hci_event_command_status_get_status(packet);
2478                 log_info("command status (inquiry), status %x", status);
2479                 if (status == ERROR_CODE_SUCCESS) {
2480                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2481                 } else {
2482                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2483                 }
2484             }
2485 #endif
2486             break;
2487 
2488         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
2489             if (size < 3) return;
2490             uint16_t num_handles = packet[2];
2491             if (size != (3u + num_handles * 4u)) return;
2492             uint16_t offset = 3;
2493             for (i=0; i<num_handles;i++){
2494                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
2495                 offset += 2u;
2496                 uint16_t num_packets = little_endian_read_16(packet, offset);
2497                 offset += 2u;
2498 
2499                 conn = hci_connection_for_handle(handle);
2500                 if (!conn){
2501                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
2502                     continue;
2503                 }
2504 
2505                 if (conn->num_packets_sent >= num_packets){
2506                     conn->num_packets_sent -= num_packets;
2507                 } else {
2508                     log_error("hci_number_completed_packets, more packet slots freed then sent.");
2509                     conn->num_packets_sent = 0;
2510                 }
2511                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
2512 
2513 #ifdef ENABLE_CLASSIC
2514                 // For SCO, we do the can_send_now_check here
2515                 hci_notify_if_sco_can_send_now();
2516 #endif
2517             }
2518             break;
2519         }
2520 
2521 #ifdef ENABLE_CLASSIC
2522         case HCI_EVENT_INQUIRY_COMPLETE:
2523             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2524                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2525                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2526                 hci_emit_event(event, sizeof(event), 1);
2527             }
2528             break;
2529         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2530             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2531                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2532             }
2533             break;
2534         case HCI_EVENT_CONNECTION_REQUEST:
2535             reverse_bd_addr(&packet[2], addr);
2536             link_type = (hci_link_type_t) packet[11];
2537 
2538             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
2539             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
2540                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
2541                 bd_addr_copy(hci_stack->decline_addr, addr);
2542                 break;
2543             }
2544 
2545             if (hci_stack->gap_classic_accept_callback != NULL){
2546                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
2547                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
2548                     bd_addr_copy(hci_stack->decline_addr, addr);
2549                     break;
2550                 }
2551             }
2552 
2553             // TODO: eval COD 8-10
2554             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
2555             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
2556             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2557             if (!conn) {
2558                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2559             }
2560             if (!conn) {
2561                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
2562                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
2563                 bd_addr_copy(hci_stack->decline_addr, addr);
2564                 break;
2565             }
2566             conn->role  = HCI_ROLE_SLAVE;
2567             conn->state = RECEIVED_CONNECTION_REQUEST;
2568             // store info about eSCO
2569             if (link_type == HCI_LINK_TYPE_ESCO){
2570                 conn->remote_supported_features[0] |= 1;
2571             }
2572             hci_run();
2573             break;
2574 
2575         case HCI_EVENT_CONNECTION_COMPLETE:
2576             // Connection management
2577             reverse_bd_addr(&packet[5], addr);
2578             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2579             addr_type = BD_ADDR_TYPE_ACL;
2580             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2581             if (conn) {
2582                 if (!packet[2]){
2583                     conn->state = OPEN;
2584                     conn->con_handle = little_endian_read_16(packet, 3);
2585 
2586                     // queue get remote feature
2587                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
2588 
2589                     // queue set supervision timeout if we're master
2590                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
2591                         connectionSetAuthenticationFlags(conn, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
2592                     }
2593 
2594                     // restart timer
2595                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2596                     btstack_run_loop_add_timer(&conn->timeout);
2597 
2598                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2599 
2600                     hci_emit_nr_connections_changed();
2601                 } else {
2602                     // connection failed
2603                     hci_handle_connection_failed(conn, packet[2]);
2604                 }
2605             }
2606             break;
2607 
2608         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2609             reverse_bd_addr(&packet[5], addr);
2610             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2611             if (packet[2]){
2612                 // connection failed
2613                 break;
2614             }
2615             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2616             if (!conn) {
2617                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2618             }
2619             if (!conn) {
2620                 break;
2621             }
2622             conn->state = OPEN;
2623             conn->con_handle = little_endian_read_16(packet, 3);
2624 
2625 #ifdef ENABLE_SCO_OVER_HCI
2626             // update SCO
2627             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2628                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2629             }
2630             // trigger can send now
2631             if (hci_have_usb_transport()){
2632                 hci_stack->sco_can_send_now = 1;
2633             }
2634 #endif
2635 #ifdef HAVE_SCO_TRANSPORT
2636             // configure sco transport
2637             if (hci_stack->sco_transport != NULL){
2638                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
2639                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
2640             }
2641 #endif
2642             break;
2643 
2644         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2645             handle = little_endian_read_16(packet, 3);
2646             conn = hci_connection_for_handle(handle);
2647             if (!conn) break;
2648             if (!packet[2]){
2649                 const uint8_t * features = &packet[5];
2650                 hci_handle_remote_features_page_0(conn, features);
2651 
2652                 // read extended features if possible
2653                 if (((hci_stack->local_supported_commands[1] & 1) != 0) && ((conn->remote_supported_features[0] & 2) != 0)) {
2654                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
2655                     break;
2656                 }
2657             }
2658             hci_handle_remote_features_received(conn);
2659             break;
2660 
2661         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2662             handle = little_endian_read_16(packet, 3);
2663             conn = hci_connection_for_handle(handle);
2664             if (!conn) break;
2665             // status = ok, page = 1
2666             if (!packet[2]) {
2667                 uint8_t page_number = packet[5];
2668                 uint8_t maximum_page_number = packet[6];
2669                 const uint8_t * features = &packet[7];
2670                 bool done = false;
2671                 switch (page_number){
2672                     case 1:
2673                         hci_handle_remote_features_page_1(conn, features);
2674                         if (maximum_page_number >= 2){
2675                             // get Secure Connections (Controller) from Page 2 if available
2676                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
2677                         } else {
2678                             // otherwise, assume SC (Controller) == SC (Host)
2679                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
2680                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2681                             }
2682                             done = true;
2683                         }
2684                         break;
2685                     case 2:
2686                         hci_handle_remote_features_page_2(conn, features);
2687                         done = true;
2688                         break;
2689                     default:
2690                         break;
2691                 }
2692                 if (!done) break;
2693             }
2694             hci_handle_remote_features_received(conn);
2695             break;
2696 
2697         case HCI_EVENT_LINK_KEY_REQUEST:
2698             // request handled by hci_run()
2699             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
2700             break;
2701 
2702         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2703             hci_event_link_key_request_get_bd_addr(packet, addr);
2704             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2705             if (!conn) break;
2706 
2707             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
2708 
2709             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2710             // Change Connection Encryption keeps link key type
2711             if (link_key_type != CHANGED_COMBINATION_KEY){
2712                 conn->link_key_type = link_key_type;
2713             }
2714             // cache link key. link keys stored in little-endian format for legacy reasons
2715             memcpy(&conn->link_key, &packet[8], 16);
2716 
2717             // only store link key:
2718             // - if bondable enabled
2719             if (hci_stack->bondable == false) break;
2720             // - if security level sufficient
2721             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
2722             // - for SSP, also check if remote side requested bonding as well
2723             if (conn->link_key_type != COMBINATION_KEY){
2724                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2725                 if (!remote_bonding){
2726                     break;
2727                 }
2728             }
2729             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2730             break;
2731         }
2732 
2733         case HCI_EVENT_PIN_CODE_REQUEST:
2734             hci_event_pin_code_request_get_bd_addr(packet, addr);
2735             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2736             if (!conn) break;
2737 
2738             hci_pairing_started(conn, false);
2739             // abort pairing if: non-bondable mode (event is not forwarded to app)
2740             if (!hci_stack->bondable ){
2741                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
2742                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
2743                 hci_run();
2744                 return;
2745             }
2746             // abort pairing if: Secure Connections Only mode (event is not forwarded to app)
2747             if (hci_stack->gap_secure_connections_only_mode){
2748                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
2749                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2750                 hci_run();
2751                 return;
2752             }
2753             break;
2754 
2755         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
2756             hci_event_io_capability_response_get_bd_addr(packet, addr);
2757             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2758             if (!conn) break;
2759 
2760             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
2761             hci_pairing_started(conn, true);
2762             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
2763             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
2764             break;
2765 
2766         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2767             hci_event_io_capability_response_get_bd_addr(packet, addr);
2768             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2769             if (!conn) break;
2770 
2771             hci_connection_timestamp(conn);
2772 
2773             hci_pairing_started(conn, true);
2774 
2775             // assess security
2776             if ((hci_stack->gap_secure_connections_only_mode || (conn->requested_security_level == LEVEL_4)) && !hci_remote_sc_enabled(conn)){
2777                 log_info("Level 4 required, but SC not supported -> abort");
2778                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2779                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2780                 break;
2781             }
2782 
2783 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
2784             if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
2785                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
2786             } else {
2787                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2788             }
2789 #endif
2790             break;
2791 
2792 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2793         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
2794             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2795             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_REMOTE_OOB_DATA_REPLY);
2796             break;
2797 #endif
2798 
2799         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2800             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
2801             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2802             if (!conn) break;
2803             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
2804                 if (hci_stack->ssp_auto_accept){
2805                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
2806                 };
2807             } else {
2808                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2809                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
2810                 // don't forward event to app
2811                 hci_run();
2812                 return;
2813             }
2814             break;
2815 
2816         case HCI_EVENT_USER_PASSKEY_REQUEST:
2817             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
2818             if (hci_stack->ssp_auto_accept){
2819                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
2820             };
2821             break;
2822 
2823         case HCI_EVENT_MODE_CHANGE:
2824             handle = hci_event_mode_change_get_handle(packet);
2825             conn = hci_connection_for_handle(handle);
2826             if (!conn) break;
2827             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2828             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2829             break;
2830 #endif
2831 
2832         case HCI_EVENT_ENCRYPTION_CHANGE:
2833             handle = hci_event_encryption_change_get_connection_handle(packet);
2834             conn = hci_connection_for_handle(handle);
2835             if (!conn) break;
2836             if (hci_event_encryption_change_get_status(packet) == 0u) {
2837                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
2838                 if (encryption_enabled){
2839                     if (hci_is_le_connection(conn)){
2840                         // For LE, we accept connection as encrypted
2841                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2842                     }
2843 #ifdef ENABLE_CLASSIC
2844                     else {
2845 
2846                         // dedicated bonding: send result and disconnect
2847                         if (conn->bonding_flags & BONDING_DEDICATED){
2848                             conn->bonding_flags &= ~BONDING_DEDICATED;
2849                             conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2850                             conn->bonding_status = packet[2];
2851                             break;
2852                         }
2853 
2854                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
2855                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type) != 0;
2856                         bool connected_uses_aes_ccm = encryption_enabled == 2;
2857                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
2858                             log_info("SC during pairing, but only E0 now -> abort");
2859                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2860                             break;
2861                         }
2862 
2863                         if ((hci_stack->local_supported_commands[0] & 0x80) != 0){
2864                             // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
2865                             conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
2866                         } else {
2867                             // if not, pretend everything is perfect
2868                             hci_handle_read_encryption_key_size_complete(conn, 16);
2869                         }
2870                     }
2871 #endif
2872                 } else {
2873                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
2874                 }
2875             }
2876 
2877             break;
2878 
2879 #ifdef ENABLE_CLASSIC
2880         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2881             handle = hci_event_authentication_complete_get_connection_handle(packet);
2882             conn = hci_connection_for_handle(handle);
2883             if (!conn) break;
2884 
2885             // clear authentication active flag
2886             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
2887             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
2888 
2889             // authenticated only if auth status == 0
2890             if (hci_event_authentication_complete_get_status(packet) == 0){
2891                 // authenticated
2892                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
2893 
2894                 // If not already encrypted, start encryption
2895                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
2896                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2897                     break;
2898                 }
2899             }
2900 
2901             // emit updated security level
2902             conn->requested_security_level = LEVEL_0;
2903             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2904             break;
2905 
2906         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
2907             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
2908             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2909             if (!conn) break;
2910 
2911             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
2912             break;
2913 #endif
2914 
2915         // HCI_EVENT_DISCONNECTION_COMPLETE
2916         // has been split, to first notify stack before shutting connection down
2917         // see end of function, too.
2918         case HCI_EVENT_DISCONNECTION_COMPLETE:
2919             if (packet[2]) break;   // status != 0
2920             handle = little_endian_read_16(packet, 3);
2921             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
2922             if (hci_stack->acl_fragmentation_total_size > 0u) {
2923                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2924                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
2925                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
2926                     hci_stack->acl_fragmentation_total_size = 0;
2927                     hci_stack->acl_fragmentation_pos = 0;
2928                     if (release_buffer){
2929                         hci_release_packet_buffer();
2930                     }
2931                 }
2932             }
2933 
2934             conn = hci_connection_for_handle(handle);
2935             if (!conn) break;
2936 #ifdef ENABLE_CLASSIC
2937             // pairing failed if it was ongoing
2938             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
2939 #endif
2940             // mark connection for shutdown
2941             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2942 
2943             // emit dedicatd bonding event
2944             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2945                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2946             }
2947 
2948 #ifdef ENABLE_BLE
2949 #ifdef ENABLE_LE_PERIPHERAL
2950             // re-enable advertisements for le connections if active
2951             if (hci_is_le_connection(conn)){
2952                 hci_update_advertisements_enabled_for_current_roles();
2953             }
2954 #endif
2955 #endif
2956             break;
2957 
2958         case HCI_EVENT_HARDWARE_ERROR:
2959             log_error("Hardware Error: 0x%02x", packet[2]);
2960             if (hci_stack->hardware_error_callback){
2961                 (*hci_stack->hardware_error_callback)(packet[2]);
2962             } else {
2963                 // if no special requests, just reboot stack
2964                 hci_power_control_off();
2965                 hci_power_control_on();
2966             }
2967             break;
2968 
2969 #ifdef ENABLE_CLASSIC
2970         case HCI_EVENT_ROLE_CHANGE:
2971             if (packet[2]) break;   // status != 0
2972             reverse_bd_addr(&packet[3], addr);
2973             addr_type = BD_ADDR_TYPE_ACL;
2974             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2975             if (!conn) break;
2976             conn->role = packet[9];
2977             break;
2978 #endif
2979 
2980         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2981             // release packet buffer only for asynchronous transport and if there are not further fragements
2982             if (hci_transport_synchronous()) {
2983                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2984                 return; // instead of break: to avoid re-entering hci_run()
2985             }
2986             hci_stack->acl_fragmentation_tx_active = 0;
2987             if (hci_stack->acl_fragmentation_total_size) break;
2988             hci_release_packet_buffer();
2989 
2990             // L2CAP receives this event via the hci_emit_event below
2991 
2992 #ifdef ENABLE_CLASSIC
2993             // For SCO, we do the can_send_now_check here
2994             hci_notify_if_sco_can_send_now();
2995 #endif
2996             break;
2997 
2998 #ifdef ENABLE_CLASSIC
2999         case HCI_EVENT_SCO_CAN_SEND_NOW:
3000             // For SCO, we do the can_send_now_check here
3001             hci_stack->sco_can_send_now = 1;
3002             hci_notify_if_sco_can_send_now();
3003             return;
3004 
3005         // explode inquriy results for easier consumption
3006         case HCI_EVENT_INQUIRY_RESULT:
3007         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3008         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3009             gap_inquiry_explode(packet, size);
3010             break;
3011 #endif
3012 
3013 #ifdef ENABLE_BLE
3014         case HCI_EVENT_LE_META:
3015             switch (packet[2]){
3016 #ifdef ENABLE_LE_CENTRAL
3017                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3018                     // log_info("advertising report received");
3019                     if (!hci_stack->le_scanning_enabled) break;
3020                     le_handle_advertisement_report(packet, size);
3021                     break;
3022 #endif
3023                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3024 					event_handle_le_connection_complete(packet);
3025                     break;
3026 
3027                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3028                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3029                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3030                     conn = hci_connection_for_handle(handle);
3031                     if (!conn) break;
3032                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3033                     break;
3034 
3035                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3036                     // connection
3037                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3038                     conn = hci_connection_for_handle(handle);
3039                     if (conn) {
3040                         // read arguments
3041                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3042                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3043                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3044                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3045 
3046                         // validate against current connection parameter range
3047                         le_connection_parameter_range_t existing_range;
3048                         gap_get_connection_parameter_range(&existing_range);
3049                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3050                         if (update_parameter){
3051                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3052                             conn->le_conn_interval_min = le_conn_interval_min;
3053                             conn->le_conn_interval_max = le_conn_interval_max;
3054                             conn->le_conn_latency = le_conn_latency;
3055                             conn->le_supervision_timeout = le_supervision_timeout;
3056                         } else {
3057                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3058                         }
3059                     }
3060                     break;
3061 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3062                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3063                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3064                     conn = hci_connection_for_handle(handle);
3065                     if (conn) {
3066                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3067                     }
3068                     break;
3069 #endif
3070                 default:
3071                     break;
3072             }
3073             break;
3074 #endif
3075         case HCI_EVENT_VENDOR_SPECIFIC:
3076             // Vendor specific commands often create vendor specific event instead of num completed packets
3077             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
3078             switch (hci_stack->manufacturer){
3079                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
3080                     hci_stack->num_cmd_packets = 1;
3081                     break;
3082                 default:
3083                     break;
3084             }
3085             break;
3086         default:
3087             break;
3088     }
3089 
3090     handle_event_for_current_stack_state(packet, size);
3091 
3092     // notify upper stack
3093 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
3094 
3095     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
3096     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
3097 		handle = little_endian_read_16(packet, 3);
3098 		hci_connection_t * aConn = hci_connection_for_handle(handle);
3099 		// discard connection if app did not trigger a reconnect in the event handler
3100 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
3101 			hci_shutdown_connection(aConn);
3102 		}
3103     }
3104 
3105 	// execute main loop
3106 	hci_run();
3107 }
3108 
3109 #ifdef ENABLE_CLASSIC
3110 
3111 #ifdef ENABLE_SCO_OVER_HCI
3112 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
3113 static void sco_schedule_tx(hci_connection_t * conn);
3114 
3115 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
3116     log_debug("SCO TX Timeout");
3117     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
3118     hci_connection_t * conn = hci_connection_for_handle(con_handle);
3119     if (!conn) return;
3120 
3121     // trigger send
3122     conn->sco_tx_ready = 1;
3123     // extra packet if CVSD but SCO buffer is too short
3124     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
3125         conn->sco_tx_ready++;
3126     }
3127     hci_notify_if_sco_can_send_now();
3128 }
3129 
3130 
3131 #define SCO_TX_AFTER_RX_MS (6)
3132 
3133 static void sco_schedule_tx(hci_connection_t * conn){
3134 
3135     uint32_t now = btstack_run_loop_get_time_ms();
3136     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
3137     int time_delta_ms = sco_tx_ms - now;
3138 
3139     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
3140 
3141     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
3142     btstack_run_loop_set_timer(timer, time_delta_ms);
3143     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
3144     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
3145     btstack_run_loop_add_timer(timer);
3146 }
3147 #endif
3148 
3149 static void sco_handler(uint8_t * packet, uint16_t size){
3150     // lookup connection struct
3151     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
3152     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
3153     if (!conn) return;
3154 
3155 #ifdef ENABLE_SCO_OVER_HCI
3156     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
3157     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
3158         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
3159             packet[2] = 0x3c;
3160             memmove(&packet[3], &packet[23], 63);
3161             size = 63;
3162         }
3163     }
3164 
3165     if (hci_have_usb_transport()){
3166         // Nothing to do
3167     } else {
3168         // 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);
3169         if (hci_stack->synchronous_flow_control_enabled == 0){
3170             uint32_t now = btstack_run_loop_get_time_ms();
3171 
3172             if (!conn->sco_rx_valid){
3173                 // ignore first 10 packets
3174                 conn->sco_rx_count++;
3175                 // log_debug("sco rx count %u", conn->sco_rx_count);
3176                 if (conn->sco_rx_count == 10) {
3177                     // use first timestamp as is and pretent it just started
3178                     conn->sco_rx_ms = now;
3179                     conn->sco_rx_valid = 1;
3180                     conn->sco_rx_count = 0;
3181                     sco_schedule_tx(conn);
3182                 }
3183             } else {
3184                 // track expected arrival timme
3185                 conn->sco_rx_count++;
3186                 conn->sco_rx_ms += 7;
3187                 int delta = (int32_t) (now - conn->sco_rx_ms);
3188                 if (delta > 0){
3189                     conn->sco_rx_ms++;
3190                 }
3191                 // log_debug("sco rx %u", conn->sco_rx_ms);
3192                 sco_schedule_tx(conn);
3193             }
3194         }
3195     }
3196 #endif
3197 
3198     // deliver to app
3199     if (hci_stack->sco_packet_handler) {
3200         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
3201     }
3202 
3203 #ifdef HAVE_SCO_TRANSPORT
3204     // We can send one packet for each received packet
3205     conn->sco_tx_ready++;
3206     hci_notify_if_sco_can_send_now();
3207 #endif
3208 
3209 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3210     conn->num_packets_completed++;
3211     hci_stack->host_completed_packets = 1;
3212     hci_run();
3213 #endif
3214 }
3215 #endif
3216 
3217 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
3218     hci_dump_packet(packet_type, 1, packet, size);
3219     switch (packet_type) {
3220         case HCI_EVENT_PACKET:
3221             event_handler(packet, size);
3222             break;
3223         case HCI_ACL_DATA_PACKET:
3224             acl_handler(packet, size);
3225             break;
3226 #ifdef ENABLE_CLASSIC
3227         case HCI_SCO_DATA_PACKET:
3228             sco_handler(packet, size);
3229             break;
3230 #endif
3231         default:
3232             break;
3233     }
3234 }
3235 
3236 /**
3237  * @brief Add event packet handler.
3238  */
3239 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3240     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3241 }
3242 
3243 
3244 /** Register HCI packet handlers */
3245 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3246     hci_stack->acl_packet_handler = handler;
3247 }
3248 
3249 #ifdef ENABLE_CLASSIC
3250 /**
3251  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
3252  */
3253 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
3254     hci_stack->sco_packet_handler = handler;
3255 }
3256 #endif
3257 
3258 static void hci_state_reset(void){
3259     // no connections yet
3260     hci_stack->connections = NULL;
3261 
3262     // keep discoverable/connectable as this has been requested by the client(s)
3263     // hci_stack->discoverable = 0;
3264     // hci_stack->connectable = 0;
3265     // hci_stack->bondable = 1;
3266     // hci_stack->own_addr_type = 0;
3267 
3268     // buffer is free
3269     hci_stack->hci_packet_buffer_reserved = 0;
3270 
3271     // no pending cmds
3272     hci_stack->decline_reason = 0;
3273     hci_stack->new_scan_enable_value = 0xff;
3274 
3275     hci_stack->secure_connections_active = false;
3276 
3277 #ifdef ENABLE_CLASSIC
3278     hci_stack->new_page_scan_interval = 0xffff;
3279     hci_stack->new_page_scan_window = 0xffff;
3280     hci_stack->new_page_scan_type = 0xff;
3281     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
3282 #endif
3283 
3284 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3285     hci_stack->classic_read_local_oob_data = true;
3286 #endif
3287 
3288     // LE
3289 #ifdef ENABLE_BLE
3290     memset(hci_stack->le_random_address, 0, 6);
3291     hci_stack->le_random_address_set = 0;
3292 #endif
3293 #ifdef ENABLE_LE_CENTRAL
3294     hci_stack->le_scanning_active  = false;
3295     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3296     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3297     hci_stack->le_whitelist_capacity = 0;
3298 #endif
3299 #ifdef ENABLE_LE_PERIPHERAL
3300     hci_stack->le_advertisements_active = false;
3301     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PARAMS_SET) != 0){
3302         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3303     }
3304     if (hci_stack->le_advertisements_data != NULL){
3305         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3306     }
3307 #endif
3308 }
3309 
3310 #ifdef ENABLE_CLASSIC
3311 /**
3312  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3313  */
3314 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3315     // store and open remote device db
3316     hci_stack->link_key_db = link_key_db;
3317     if (hci_stack->link_key_db) {
3318         hci_stack->link_key_db->open();
3319     }
3320 }
3321 #endif
3322 
3323 void hci_init(const hci_transport_t *transport, const void *config){
3324 
3325 #ifdef HAVE_MALLOC
3326     if (!hci_stack) {
3327         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3328     }
3329 #else
3330     hci_stack = &hci_stack_static;
3331 #endif
3332     memset(hci_stack, 0, sizeof(hci_stack_t));
3333 
3334     // reference to use transport layer implementation
3335     hci_stack->hci_transport = transport;
3336 
3337     // reference to used config
3338     hci_stack->config = config;
3339 
3340     // setup pointer for outgoing packet buffer
3341     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3342 
3343     // max acl payload size defined in config.h
3344     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3345 
3346     // register packet handlers with transport
3347     transport->register_packet_handler(&packet_handler);
3348 
3349     hci_stack->state = HCI_STATE_OFF;
3350 
3351     // class of device
3352     hci_stack->class_of_device = 0x007a020c; // Smartphone
3353 
3354     // bondable by default
3355     hci_stack->bondable = 1;
3356 
3357 #ifdef ENABLE_CLASSIC
3358     // classic name
3359     hci_stack->local_name = default_classic_name;
3360 
3361     // Master slave policy
3362     hci_stack->master_slave_policy = 1;
3363 
3364     // Allow Role Switch
3365     hci_stack->allow_role_switch = 1;
3366 
3367     // Default / minimum security level = 2
3368     hci_stack->gap_security_level = LEVEL_2;
3369 
3370     // Default Security Mode 4
3371     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
3372 
3373     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3374     hci_stack->gap_required_encyrption_key_size = 7;
3375 
3376     // Link Supervision Timeout
3377     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3378 
3379 #endif
3380 
3381     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3382     hci_stack->ssp_enable = 1;
3383     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3384     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3385     hci_stack->ssp_auto_accept = 1;
3386 
3387     // Secure Connections: enable (requires support from Controller)
3388     hci_stack->secure_connections_enable = true;
3389 
3390     // voice setting - signed 16 bit pcm data with CVSD over the air
3391     hci_stack->sco_voice_setting = 0x60;
3392 
3393 #ifdef ENABLE_LE_CENTRAL
3394     // connection parameter to use for outgoing connections
3395     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3396     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3397     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3398     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3399     hci_stack->le_connection_latency      = 4;         // 4
3400     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3401     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3402     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3403 
3404     // default LE Scanning
3405     hci_stack->le_scan_type     =   0x1; // active
3406     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3407     hci_stack->le_scan_window   =  0x30; //  30 ms
3408 #endif
3409 
3410 #ifdef ENABLE_LE_PERIPHERAL
3411     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3412 #endif
3413 
3414     // connection parameter range used to answer connection parameter update requests in l2cap
3415     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3416     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3417     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3418     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3419     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3420     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3421 
3422     hci_state_reset();
3423 }
3424 
3425 void hci_deinit(void){
3426 #ifdef HAVE_MALLOC
3427     if (hci_stack) {
3428         free(hci_stack);
3429     }
3430 #endif
3431     hci_stack = NULL;
3432 
3433 #ifdef ENABLE_CLASSIC
3434     disable_l2cap_timeouts = 0;
3435 #endif
3436 }
3437 
3438 /**
3439  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3440  */
3441 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3442     hci_stack->chipset = chipset_driver;
3443 
3444     // reset chipset driver - init is also called on power_up
3445     if (hci_stack->chipset && hci_stack->chipset->init){
3446         hci_stack->chipset->init(hci_stack->config);
3447     }
3448 }
3449 
3450 /**
3451  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3452  */
3453 void hci_set_control(const btstack_control_t *hardware_control){
3454     // references to used control implementation
3455     hci_stack->control = hardware_control;
3456     // init with transport config
3457     hardware_control->init(hci_stack->config);
3458 }
3459 
3460 void hci_close(void){
3461 
3462 #ifdef ENABLE_CLASSIC
3463     // close remote device db
3464     if (hci_stack->link_key_db) {
3465         hci_stack->link_key_db->close();
3466     }
3467 #endif
3468 
3469     btstack_linked_list_iterator_t lit;
3470     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3471     while (btstack_linked_list_iterator_has_next(&lit)){
3472         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3473         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3474         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3475         hci_shutdown_connection(connection);
3476     }
3477 
3478     hci_power_control(HCI_POWER_OFF);
3479 
3480 #ifdef HAVE_MALLOC
3481     free(hci_stack);
3482 #endif
3483     hci_stack = NULL;
3484 }
3485 
3486 #ifdef HAVE_SCO_TRANSPORT
3487 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3488     hci_stack->sco_transport = sco_transport;
3489     sco_transport->register_packet_handler(&packet_handler);
3490 }
3491 #endif
3492 
3493 #ifdef ENABLE_CLASSIC
3494 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3495     // validate ranage and set
3496     if (encryption_key_size < 7)  return;
3497     if (encryption_key_size > 16) return;
3498     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3499 }
3500 
3501 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
3502     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
3503         hci_stack->gap_security_mode = security_mode;
3504         return ERROR_CODE_SUCCESS;
3505     } else {
3506         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3507     }
3508 }
3509 
3510 gap_security_mode_t gap_get_security_mode(void){
3511     return hci_stack->gap_security_mode;
3512 }
3513 
3514 void gap_set_security_level(gap_security_level_t security_level){
3515     hci_stack->gap_security_level = security_level;
3516 }
3517 
3518 gap_security_level_t gap_get_security_level(void){
3519     if (hci_stack->gap_secure_connections_only_mode){
3520         return LEVEL_4;
3521     }
3522     return hci_stack->gap_security_level;
3523 }
3524 
3525 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
3526     hci_stack->gap_minimal_service_security_level = security_level;
3527 }
3528 
3529 void gap_set_secure_connections_only_mode(bool enable){
3530     hci_stack->gap_secure_connections_only_mode = enable;
3531 }
3532 
3533 bool gap_get_secure_connections_only_mode(void){
3534     return hci_stack->gap_secure_connections_only_mode;
3535 }
3536 #endif
3537 
3538 #ifdef ENABLE_CLASSIC
3539 void gap_set_class_of_device(uint32_t class_of_device){
3540     hci_stack->class_of_device = class_of_device;
3541 }
3542 
3543 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3544     hci_stack->default_link_policy_settings = default_link_policy_settings;
3545 }
3546 
3547 void gap_set_allow_role_switch(bool allow_role_switch){
3548     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3549 }
3550 
3551 uint8_t hci_get_allow_role_switch(void){
3552     return  hci_stack->allow_role_switch;
3553 }
3554 
3555 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
3556     hci_stack->link_supervision_timeout = link_supervision_timeout;
3557 }
3558 
3559 void hci_disable_l2cap_timeout_check(void){
3560     disable_l2cap_timeouts = 1;
3561 }
3562 #endif
3563 
3564 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3565 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3566 void hci_set_bd_addr(bd_addr_t addr){
3567     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3568     hci_stack->custom_bd_addr_set = 1;
3569 }
3570 #endif
3571 
3572 // State-Module-Driver overview
3573 // state                    module  low-level
3574 // HCI_STATE_OFF             off      close
3575 // HCI_STATE_INITIALIZING,   on       open
3576 // HCI_STATE_WORKING,        on       open
3577 // HCI_STATE_HALTING,        on       open
3578 // HCI_STATE_SLEEPING,    off/sleep   close
3579 // HCI_STATE_FALLING_ASLEEP  on       open
3580 
3581 static int hci_power_control_on(void){
3582 
3583     // power on
3584     int err = 0;
3585     if (hci_stack->control && hci_stack->control->on){
3586         err = (*hci_stack->control->on)();
3587     }
3588     if (err){
3589         log_error( "POWER_ON failed");
3590         hci_emit_hci_open_failed();
3591         return err;
3592     }
3593 
3594     // int chipset driver
3595     if (hci_stack->chipset && hci_stack->chipset->init){
3596         hci_stack->chipset->init(hci_stack->config);
3597     }
3598 
3599     // init transport
3600     if (hci_stack->hci_transport->init){
3601         hci_stack->hci_transport->init(hci_stack->config);
3602     }
3603 
3604     // open transport
3605     err = hci_stack->hci_transport->open();
3606     if (err){
3607         log_error( "HCI_INIT failed, turning Bluetooth off again");
3608         if (hci_stack->control && hci_stack->control->off){
3609             (*hci_stack->control->off)();
3610         }
3611         hci_emit_hci_open_failed();
3612         return err;
3613     }
3614     return 0;
3615 }
3616 
3617 static void hci_power_control_off(void){
3618 
3619     log_info("hci_power_control_off");
3620 
3621     // close low-level device
3622     hci_stack->hci_transport->close();
3623 
3624     log_info("hci_power_control_off - hci_transport closed");
3625 
3626     // power off
3627     if (hci_stack->control && hci_stack->control->off){
3628         (*hci_stack->control->off)();
3629     }
3630 
3631     log_info("hci_power_control_off - control closed");
3632 
3633     hci_stack->state = HCI_STATE_OFF;
3634 }
3635 
3636 static void hci_power_control_sleep(void){
3637 
3638     log_info("hci_power_control_sleep");
3639 
3640 #if 0
3641     // don't close serial port during sleep
3642 
3643     // close low-level device
3644     hci_stack->hci_transport->close(hci_stack->config);
3645 #endif
3646 
3647     // sleep mode
3648     if (hci_stack->control && hci_stack->control->sleep){
3649         (*hci_stack->control->sleep)();
3650     }
3651 
3652     hci_stack->state = HCI_STATE_SLEEPING;
3653 }
3654 
3655 static int hci_power_control_wake(void){
3656 
3657     log_info("hci_power_control_wake");
3658 
3659     // wake on
3660     if (hci_stack->control && hci_stack->control->wake){
3661         (*hci_stack->control->wake)();
3662     }
3663 
3664 #if 0
3665     // open low-level device
3666     int err = hci_stack->hci_transport->open(hci_stack->config);
3667     if (err){
3668         log_error( "HCI_INIT failed, turning Bluetooth off again");
3669         if (hci_stack->control && hci_stack->control->off){
3670             (*hci_stack->control->off)();
3671         }
3672         hci_emit_hci_open_failed();
3673         return err;
3674     }
3675 #endif
3676 
3677     return 0;
3678 }
3679 
3680 static void hci_power_transition_to_initializing(void){
3681     // set up state machine
3682     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
3683     hci_stack->hci_packet_buffer_reserved = 0;
3684     hci_stack->state = HCI_STATE_INITIALIZING;
3685     hci_stack->substate = HCI_INIT_SEND_RESET;
3686 }
3687 
3688 // returns error
3689 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
3690     int err;
3691     switch (power_mode){
3692         case HCI_POWER_ON:
3693             err = hci_power_control_on();
3694             if (err != 0) {
3695                 log_error("hci_power_control_on() error %d", err);
3696                 return err;
3697             }
3698             hci_power_transition_to_initializing();
3699             break;
3700         case HCI_POWER_OFF:
3701             // do nothing
3702             break;
3703         case HCI_POWER_SLEEP:
3704             // do nothing (with SLEEP == OFF)
3705             break;
3706         default:
3707             btstack_assert(false);
3708             break;
3709     }
3710     return ERROR_CODE_SUCCESS;
3711 }
3712 
3713 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
3714     switch (power_mode){
3715         case HCI_POWER_ON:
3716             // do nothing
3717             break;
3718         case HCI_POWER_OFF:
3719             // no connections yet, just turn it off
3720             hci_power_control_off();
3721             break;
3722         case HCI_POWER_SLEEP:
3723             // no connections yet, just turn it off
3724             hci_power_control_sleep();
3725             break;
3726         default:
3727             btstack_assert(false);
3728             break;
3729     }
3730     return ERROR_CODE_SUCCESS;
3731 }
3732 
3733 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
3734     switch (power_mode){
3735         case HCI_POWER_ON:
3736             // do nothing
3737             break;
3738         case HCI_POWER_OFF:
3739             // see hci_run
3740             hci_stack->state = HCI_STATE_HALTING;
3741             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3742             break;
3743         case HCI_POWER_SLEEP:
3744             // see hci_run
3745             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3746             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3747             break;
3748         default:
3749             btstack_assert(false);
3750             break;
3751     }
3752     return ERROR_CODE_SUCCESS;
3753 }
3754 
3755 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
3756     switch (power_mode){
3757         case HCI_POWER_ON:
3758             hci_power_transition_to_initializing();
3759             break;
3760         case HCI_POWER_OFF:
3761             // do nothing
3762             break;
3763         case HCI_POWER_SLEEP:
3764             // see hci_run
3765             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3766             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3767             break;
3768         default:
3769             btstack_assert(false);
3770             break;
3771     }
3772     return ERROR_CODE_SUCCESS;
3773 }
3774 
3775 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
3776     switch (power_mode){
3777         case HCI_POWER_ON:
3778 
3779 #ifdef HAVE_PLATFORM_IPHONE_OS
3780             // nothing to do, if H4 supports power management
3781                     if (btstack_control_iphone_power_management_enabled()){
3782                         hci_stack->state = HCI_STATE_INITIALIZING;
3783                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3784                         break;
3785                     }
3786 #endif
3787             hci_power_transition_to_initializing();
3788             break;
3789         case HCI_POWER_OFF:
3790             // see hci_run
3791             hci_stack->state = HCI_STATE_HALTING;
3792             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3793             break;
3794         case HCI_POWER_SLEEP:
3795             // do nothing
3796             break;
3797         default:
3798             btstack_assert(false);
3799             break;
3800     }
3801     return ERROR_CODE_SUCCESS;
3802 }
3803 
3804 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
3805     int err;
3806     switch (power_mode){
3807         case HCI_POWER_ON:
3808 #ifdef HAVE_PLATFORM_IPHONE_OS
3809             // nothing to do, if H4 supports power management
3810                     if (btstack_control_iphone_power_management_enabled()){
3811                         hci_stack->state = HCI_STATE_INITIALIZING;
3812                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3813                         hci_update_scan_enable();
3814                         break;
3815                     }
3816 #endif
3817             err = hci_power_control_wake();
3818             if (err) return err;
3819             hci_power_transition_to_initializing();
3820             break;
3821         case HCI_POWER_OFF:
3822             hci_stack->state = HCI_STATE_HALTING;
3823             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3824             break;
3825         case HCI_POWER_SLEEP:
3826             // do nothing
3827             break;
3828         default:
3829             btstack_assert(false);
3830             break;
3831     }
3832     return ERROR_CODE_SUCCESS;
3833 }
3834 
3835 int hci_power_control(HCI_POWER_MODE power_mode){
3836     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
3837     int err = 0;
3838     switch (hci_stack->state){
3839         case HCI_STATE_OFF:
3840             err = hci_power_control_state_off(power_mode);
3841             break;
3842         case HCI_STATE_INITIALIZING:
3843             err = hci_power_control_state_initializing(power_mode);
3844             break;
3845         case HCI_STATE_WORKING:
3846             err = hci_power_control_state_working(power_mode);
3847             break;
3848         case HCI_STATE_HALTING:
3849             err = hci_power_control_state_halting(power_mode);
3850             break;
3851         case HCI_STATE_FALLING_ASLEEP:
3852             err = hci_power_control_state_falling_asleep(power_mode);
3853             break;
3854         case HCI_STATE_SLEEPING:
3855             err = hci_power_control_state_sleeping(power_mode);
3856             break;
3857         default:
3858             btstack_assert(false);
3859             break;
3860     }
3861     if (err != 0){
3862         return err;
3863     }
3864 
3865     // create internal event
3866 	hci_emit_state();
3867 
3868 	// trigger next/first action
3869 	hci_run();
3870 
3871     return 0;
3872 }
3873 
3874 
3875 #ifdef ENABLE_CLASSIC
3876 
3877 static void hci_update_scan_enable(void){
3878     // 2 = page scan, 1 = inq scan
3879     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
3880     hci_run();
3881 }
3882 
3883 void gap_discoverable_control(uint8_t enable){
3884     if (enable) enable = 1; // normalize argument
3885 
3886     if (hci_stack->discoverable == enable){
3887         hci_emit_discoverable_enabled(hci_stack->discoverable);
3888         return;
3889     }
3890 
3891     hci_stack->discoverable = enable;
3892     hci_update_scan_enable();
3893 }
3894 
3895 void gap_connectable_control(uint8_t enable){
3896     if (enable) enable = 1; // normalize argument
3897 
3898     // don't emit event
3899     if (hci_stack->connectable == enable) return;
3900 
3901     hci_stack->connectable = enable;
3902     hci_update_scan_enable();
3903 }
3904 #endif
3905 
3906 void gap_local_bd_addr(bd_addr_t address_buffer){
3907     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3908 }
3909 
3910 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3911 static void hci_host_num_completed_packets(void){
3912 
3913     // create packet manually as arrays are not supported and num_commands should not get reduced
3914     hci_reserve_packet_buffer();
3915     uint8_t * packet = hci_get_outgoing_packet_buffer();
3916 
3917     uint16_t size = 0;
3918     uint16_t num_handles = 0;
3919     packet[size++] = 0x35;
3920     packet[size++] = 0x0c;
3921     size++;  // skip param len
3922     size++;  // skip num handles
3923 
3924     // add { handle, packets } entries
3925     btstack_linked_item_t * it;
3926     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3927         hci_connection_t * connection = (hci_connection_t *) it;
3928         if (connection->num_packets_completed){
3929             little_endian_store_16(packet, size, connection->con_handle);
3930             size += 2;
3931             little_endian_store_16(packet, size, connection->num_packets_completed);
3932             size += 2;
3933             //
3934             num_handles++;
3935             connection->num_packets_completed = 0;
3936         }
3937     }
3938 
3939     packet[2] = size - 3;
3940     packet[3] = num_handles;
3941 
3942     hci_stack->host_completed_packets = 0;
3943 
3944     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3945     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3946 
3947     // release packet buffer for synchronous transport implementations
3948     if (hci_transport_synchronous()){
3949         hci_release_packet_buffer();
3950         hci_emit_transport_packet_sent();
3951     }
3952 }
3953 #endif
3954 
3955 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
3956     UNUSED(ds);
3957     hci_stack->substate = HCI_HALTING_CLOSE;
3958     // allow packet handlers to defer final shutdown
3959     hci_emit_state();
3960     hci_run();
3961 }
3962 
3963 static bool hci_run_acl_fragments(void){
3964     if (hci_stack->acl_fragmentation_total_size > 0u) {
3965         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3966         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3967         if (connection) {
3968             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3969                 hci_send_acl_packet_fragments(connection);
3970                 return true;
3971             }
3972         } else {
3973             // connection gone -> discard further fragments
3974             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3975             hci_stack->acl_fragmentation_total_size = 0;
3976             hci_stack->acl_fragmentation_pos = 0;
3977         }
3978     }
3979     return false;
3980 }
3981 
3982 #ifdef ENABLE_CLASSIC
3983 static bool hci_run_general_gap_classic(void){
3984 
3985     // decline incoming connections
3986     if (hci_stack->decline_reason){
3987         uint8_t reason = hci_stack->decline_reason;
3988         hci_stack->decline_reason = 0;
3989         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3990         return true;
3991     }
3992     // write page scan activity
3993     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_interval != 0xffff) && hci_classic_supported()){
3994         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
3995         hci_stack->new_page_scan_interval = 0xffff;
3996         hci_stack->new_page_scan_window = 0xffff;
3997         return true;
3998     }
3999     // write page scan type
4000     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_type != 0xff) && hci_classic_supported()){
4001         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
4002         hci_stack->new_page_scan_type = 0xff;
4003         return true;
4004     }
4005     // send scan enable
4006     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_scan_enable_value != 0xff) && hci_classic_supported()){
4007         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
4008         hci_stack->new_scan_enable_value = 0xff;
4009         return true;
4010     }
4011     // start/stop inquiry
4012     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
4013         uint8_t duration = hci_stack->inquiry_state;
4014         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
4015         hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
4016         return true;
4017     }
4018     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
4019         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4020         hci_send_cmd(&hci_inquiry_cancel);
4021         return true;
4022     }
4023     // remote name request
4024     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4025         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4026         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4027                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4028         return true;
4029     }
4030 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4031     // Local OOB data
4032     if ((hci_stack->state == HCI_STATE_WORKING) && hci_stack->classic_read_local_oob_data){
4033         hci_stack->classic_read_local_oob_data = false;
4034         if (hci_stack->local_supported_commands[1] & 0x10u){
4035             hci_send_cmd(&hci_read_local_extended_oob_data);
4036         } else {
4037             hci_send_cmd(&hci_read_local_oob_data);
4038         }
4039     }
4040 #endif
4041     // pairing
4042     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
4043         uint8_t state = hci_stack->gap_pairing_state;
4044         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4045         uint8_t pin_code[16];
4046         switch (state){
4047             case GAP_PAIRING_STATE_SEND_PIN:
4048                 memset(pin_code, 0, 16);
4049                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
4050                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
4051                 break;
4052             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
4053                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
4054                 break;
4055             case GAP_PAIRING_STATE_SEND_PASSKEY:
4056                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
4057                 break;
4058             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
4059                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
4060                 break;
4061             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
4062                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
4063                 break;
4064             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
4065                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
4066                 break;
4067             default:
4068                 break;
4069         }
4070         return true;
4071     }
4072     return false;
4073 }
4074 #endif
4075 
4076 #ifdef ENABLE_BLE
4077 static bool hci_run_general_gap_le(void){
4078 
4079     // advertisements, active scanning, and creating connections requires random address to be set if using private address
4080 
4081     if (hci_stack->state != HCI_STATE_WORKING) return false;
4082     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
4083 
4084 
4085     // Phase 1: collect what to stop
4086 
4087     bool scanning_stop = false;
4088     bool connecting_stop = false;
4089     bool advertising_stop = false;
4090 
4091 #ifndef ENABLE_LE_CENTRAL
4092     UNUSED(scanning_stop);
4093     UNUSED(connecting_stop);
4094 #endif
4095 #ifndef ENABLE_LE_PERIPHERAL
4096     UNUSED(advertising_stop);
4097 #endif
4098 
4099     // check if whitelist needs modification
4100     bool whitelist_modification_pending = false;
4101     btstack_linked_list_iterator_t lit;
4102     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4103     while (btstack_linked_list_iterator_has_next(&lit)){
4104         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4105         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
4106             whitelist_modification_pending = true;
4107             break;
4108         }
4109     }
4110     // check if resolving list needs modification
4111     bool resolving_list_modification_pending = false;
4112 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4113     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
4114 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
4115         resolving_list_modification_pending = true;
4116     }
4117 #endif
4118 
4119 #ifdef ENABLE_LE_CENTRAL
4120     // scanning control
4121     if (hci_stack->le_scanning_active) {
4122         // stop if:
4123         // - parameter change required
4124         // - it's disabled
4125         // - whitelist change required but used for scanning
4126         // - resolving list modified
4127         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
4128         if ((hci_stack->le_scanning_param_update) ||
4129             !hci_stack->le_scanning_enabled ||
4130             scanning_uses_whitelist ||
4131             resolving_list_modification_pending){
4132 
4133             scanning_stop = true;
4134         }
4135     }
4136 #endif
4137 
4138 #ifdef ENABLE_LE_CENTRAL
4139     // connecting control
4140     bool connecting_with_whitelist;
4141     switch (hci_stack->le_connecting_state){
4142         case LE_CONNECTING_DIRECT:
4143         case LE_CONNECTING_WHITELIST:
4144             // stop connecting if:
4145             // - connecting uses white and whitelist modification pending
4146             // - if it got disabled
4147             // - resolving list modified
4148             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4149             if ((connecting_with_whitelist && whitelist_modification_pending) ||
4150                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
4151                 resolving_list_modification_pending) {
4152 
4153                 connecting_stop = true;
4154             }
4155             break;
4156         default:
4157             break;
4158     }
4159 #endif
4160 
4161 #ifdef ENABLE_LE_PERIPHERAL
4162     // le advertisement control
4163     if (hci_stack->le_advertisements_active){
4164         // stop if:
4165         // - parameter change required
4166         // - it's disabled
4167         // - whitelist change required but used for advertisement filter policy
4168         // - resolving list modified
4169         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
4170         bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
4171         if (advertising_change ||
4172             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
4173             (advertising_uses_whitelist & whitelist_modification_pending) ||
4174             resolving_list_modification_pending) {
4175 
4176             advertising_stop = true;
4177         }
4178     }
4179 #endif
4180 
4181 
4182     // Phase 2: stop everything that should be off during modifications
4183 
4184 #ifdef ENABLE_LE_CENTRAL
4185     if (scanning_stop){
4186         hci_stack->le_scanning_active = false;
4187         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4188         return true;
4189     }
4190 #endif
4191 
4192 #ifdef ENABLE_LE_CENTRAL
4193     if (connecting_stop){
4194         hci_send_cmd(&hci_le_create_connection_cancel);
4195         return true;
4196     }
4197 #endif
4198 
4199 #ifdef ENABLE_LE_PERIPHERAL
4200     if (advertising_stop){
4201         hci_stack->le_advertisements_active = false;
4202         hci_send_cmd(&hci_le_set_advertise_enable, 0);
4203         return true;
4204     }
4205 #endif
4206 
4207     // Phase 3: modify
4208 
4209 #ifdef ENABLE_LE_CENTRAL
4210     if (hci_stack->le_scanning_param_update){
4211         hci_stack->le_scanning_param_update = false;
4212         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
4213                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
4214         return true;
4215     }
4216 #endif
4217 
4218 #ifdef ENABLE_LE_PERIPHERAL
4219     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
4220         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4221         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
4222         hci_send_cmd(&hci_le_set_advertising_parameters,
4223                      hci_stack->le_advertisements_interval_min,
4224                      hci_stack->le_advertisements_interval_max,
4225                      hci_stack->le_advertisements_type,
4226                      hci_stack->le_advertisements_own_addr_type,
4227                      hci_stack->le_advertisements_direct_address_type,
4228                      hci_stack->le_advertisements_direct_address,
4229                      hci_stack->le_advertisements_channel_map,
4230                      hci_stack->le_advertisements_filter_policy);
4231         return true;
4232     }
4233     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
4234         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4235         uint8_t adv_data_clean[31];
4236         memset(adv_data_clean, 0, sizeof(adv_data_clean));
4237         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
4238                      hci_stack->le_advertisements_data_len);
4239         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
4240         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
4241         return true;
4242     }
4243     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
4244         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4245         uint8_t scan_data_clean[31];
4246         memset(scan_data_clean, 0, sizeof(scan_data_clean));
4247         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
4248                      hci_stack->le_scan_response_data_len);
4249         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
4250         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
4251         return true;
4252     }
4253 #endif
4254 
4255 
4256 #ifdef ENABLE_LE_CENTRAL
4257     // if connect with whitelist was active and is not cancelled yet, wait until next time
4258     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
4259 #endif
4260 
4261     // LE Whitelist Management
4262     if (whitelist_modification_pending){
4263         // add/remove entries
4264         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4265         while (btstack_linked_list_iterator_has_next(&lit)){
4266             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4267 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4268 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4269 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
4270 				return true;
4271 			}
4272             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
4273 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
4274                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
4275                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
4276                 return true;
4277             }
4278             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
4279 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4280 				btstack_memory_whitelist_entry_free(entry);
4281             }
4282         }
4283     }
4284 
4285 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4286     // LE Resolving List Management
4287     if (resolving_list_supported) {
4288 		uint16_t i;
4289 		switch (hci_stack->le_resolving_list_state) {
4290 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
4291 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
4292 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
4293 				return true;
4294 			case LE_RESOLVING_LIST_READ_SIZE:
4295 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
4296 				hci_send_cmd(&hci_le_read_resolving_list_size);
4297 				return true;
4298 			case LE_RESOLVING_LIST_SEND_CLEAR:
4299 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4300 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4301 							  sizeof(hci_stack->le_resolving_list_add_entries));
4302 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4303 							  sizeof(hci_stack->le_resolving_list_remove_entries));
4304 				hci_send_cmd(&hci_le_clear_resolving_list);
4305 				return true;
4306 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
4307 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4308 					uint8_t offset = i >> 3;
4309 					uint8_t mask = 1 << (i & 7);
4310 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
4311 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
4312 					bd_addr_t peer_identity_addreses;
4313 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4314 					sm_key_t peer_irk;
4315 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4316 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4317 
4318 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4319 					// trigger whitelist entry 'update' (work around for controller bug)
4320 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4321 					while (btstack_linked_list_iterator_has_next(&lit)) {
4322 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4323 						if (entry->address_type != peer_identity_addr_type) continue;
4324 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4325 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4326 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4327 					}
4328 #endif
4329 
4330 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4331 								 peer_identity_addreses);
4332 					return true;
4333 				}
4334 
4335 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
4336 
4337 				/* fall through */
4338 
4339 			case LE_RESOLVING_LIST_ADD_ENTRIES:
4340 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4341 					uint8_t offset = i >> 3;
4342 					uint8_t mask = 1 << (i & 7);
4343 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
4344 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
4345 					bd_addr_t peer_identity_addreses;
4346 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4347 					sm_key_t peer_irk;
4348 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4349 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4350 					const uint8_t *local_irk = gap_get_persistent_irk();
4351 					// command uses format specifier 'P' that stores 16-byte value without flip
4352 					uint8_t local_irk_flipped[16];
4353 					uint8_t peer_irk_flipped[16];
4354 					reverse_128(local_irk, local_irk_flipped);
4355 					reverse_128(peer_irk, peer_irk_flipped);
4356 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4357 								 peer_irk_flipped, local_irk_flipped);
4358 					return true;
4359 				}
4360 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4361 				break;
4362 
4363 			default:
4364 				break;
4365 		}
4366 	}
4367     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4368 #endif
4369 
4370     // Phase 4: restore state
4371 
4372 #ifdef ENABLE_LE_CENTRAL
4373     // re-start scanning
4374     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
4375         hci_stack->le_scanning_active = true;
4376         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
4377         return true;
4378     }
4379 #endif
4380 
4381 #ifdef ENABLE_LE_CENTRAL
4382     // re-start connecting
4383     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
4384         bd_addr_t null_addr;
4385         memset(null_addr, 0, 6);
4386         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4387         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4388         hci_send_cmd(&hci_le_create_connection,
4389                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4390                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
4391                      1,         // use whitelist
4392                      0,         // peer address type
4393                      null_addr, // peer bd addr
4394                      hci_stack->le_connection_own_addr_type,   // our addr type:
4395                      hci_stack->le_connection_interval_min,    // conn interval min
4396                      hci_stack->le_connection_interval_max,    // conn interval max
4397                      hci_stack->le_connection_latency,         // conn latency
4398                      hci_stack->le_supervision_timeout,        // conn latency
4399                      hci_stack->le_minimum_ce_length,          // min ce length
4400                      hci_stack->le_maximum_ce_length           // max ce length
4401         );
4402         return true;
4403     }
4404 #endif
4405 
4406 #ifdef ENABLE_LE_PERIPHERAL
4407     // re-start advertising
4408     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4409         // check if advertisements should be enabled given
4410         hci_stack->le_advertisements_active = true;
4411         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_advertisements_own_address);
4412         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4413         return true;
4414     }
4415 #endif
4416 
4417     return false;
4418 }
4419 #endif
4420 
4421 static bool hci_run_general_pending_commands(void){
4422     btstack_linked_item_t * it;
4423     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
4424         hci_connection_t * connection = (hci_connection_t *) it;
4425 
4426         switch(connection->state){
4427             case SEND_CREATE_CONNECTION:
4428                 switch(connection->address_type){
4429 #ifdef ENABLE_CLASSIC
4430                     case BD_ADDR_TYPE_ACL:
4431                         log_info("sending hci_create_connection");
4432                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
4433                         break;
4434 #endif
4435                     default:
4436 #ifdef ENABLE_BLE
4437 #ifdef ENABLE_LE_CENTRAL
4438                         log_info("sending hci_le_create_connection");
4439                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4440                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4441                         hci_send_cmd(&hci_le_create_connection,
4442                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4443                                      hci_stack->le_connection_scan_window,      // conn scan windows
4444                                      0,         // don't use whitelist
4445                                      connection->address_type, // peer address type
4446                                      connection->address,      // peer bd addr
4447                                      hci_stack->le_connection_own_addr_type,   // our addr type:
4448                                      hci_stack->le_connection_interval_min,    // conn interval min
4449                                      hci_stack->le_connection_interval_max,    // conn interval max
4450                                      hci_stack->le_connection_latency,         // conn latency
4451                                      hci_stack->le_supervision_timeout,        // conn latency
4452                                      hci_stack->le_minimum_ce_length,          // min ce length
4453                                      hci_stack->le_maximum_ce_length          // max ce length
4454                         );
4455                         connection->state = SENT_CREATE_CONNECTION;
4456 #endif
4457 #endif
4458                         break;
4459                 }
4460                 return true;
4461 
4462 #ifdef ENABLE_CLASSIC
4463             case RECEIVED_CONNECTION_REQUEST:
4464                 connection->role  = HCI_ROLE_SLAVE;
4465                 if (connection->address_type == BD_ADDR_TYPE_ACL){
4466                     log_info("sending hci_accept_connection_request");
4467                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4468                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4469                 }
4470                 return true;
4471 #endif
4472 
4473 #ifdef ENABLE_BLE
4474 #ifdef ENABLE_LE_CENTRAL
4475             case SEND_CANCEL_CONNECTION:
4476                 connection->state = SENT_CANCEL_CONNECTION;
4477                 hci_send_cmd(&hci_le_create_connection_cancel);
4478                 return true;
4479 #endif
4480 #endif
4481             case SEND_DISCONNECT:
4482                 connection->state = SENT_DISCONNECT;
4483                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4484                 return true;
4485 
4486             default:
4487                 break;
4488         }
4489 
4490         // no further commands if connection is about to get shut down
4491         if (connection->state == SENT_DISCONNECT) continue;
4492 
4493         if (connection->authentication_flags & AUTH_FLAG_READ_RSSI){
4494             connectionClearAuthenticationFlags(connection, AUTH_FLAG_READ_RSSI);
4495             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4496             return true;
4497         }
4498 
4499 #ifdef ENABLE_CLASSIC
4500 
4501         if (connection->authentication_flags & AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT){
4502             connectionClearAuthenticationFlags(connection, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
4503             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4504             return true;
4505         }
4506 
4507         // Handling link key request requires remote supported features
4508         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
4509             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
4510             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
4511 
4512             // lookup link key using cached key first
4513             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
4514             if (!have_link_key && (hci_stack->link_key_db != NULL)){
4515                 have_link_key = hci_stack->link_key_db->get_link_key(connection->address, connection->link_key, &connection->link_key_type);
4516             }
4517 
4518             bool sc_enabled_remote = hci_remote_sc_enabled(connection);
4519             bool sc_downgrade = have_link_key && (gap_secure_connection_for_link_key_type(connection->link_key_type) == 1) && !sc_enabled_remote;
4520             if (sc_downgrade){
4521                 log_info("Link key based on SC, but remote does not support SC -> disconnect");
4522                 connection->state = SENT_DISCONNECT;
4523                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4524                 return true;
4525             }
4526 
4527             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
4528             if (have_link_key && security_level_sufficient){
4529                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
4530             } else {
4531                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
4532             }
4533             return true;
4534         }
4535 
4536         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
4537             log_info("denying to pin request");
4538             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
4539             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4540             return true;
4541         }
4542 
4543         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
4544             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
4545             // set authentication requirements:
4546             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
4547             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
4548             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
4549             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
4550                 authreq |= 1;
4551             }
4552             bool bonding = hci_stack->bondable;
4553             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
4554                 // if we have received IO Cap Response, we're in responder role
4555                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4556                 if (bonding && !remote_bonding){
4557                     log_info("Remote not bonding, dropping local flag");
4558                     bonding = false;
4559                 }
4560             }
4561             if (bonding){
4562                 if (connection->bonding_flags & BONDING_DEDICATED){
4563                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4564                 } else {
4565                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4566                 }
4567             }
4568             uint8_t have_oob_data = 0;
4569 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4570             if (connection->classic_oob_c_192 != NULL){
4571                     have_oob_data |= 1;
4572             }
4573             if (connection->classic_oob_c_256 != NULL){
4574                 have_oob_data |= 2;
4575             }
4576 #endif
4577             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
4578             return true;
4579         }
4580 
4581         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
4582             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
4583             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4584             return true;
4585         }
4586 
4587 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4588         if (connection->authentication_flags & SEND_REMOTE_OOB_DATA_REPLY){
4589             connectionClearAuthenticationFlags(connection, SEND_REMOTE_OOB_DATA_REPLY);
4590             const uint8_t zero[16] = { 0 };
4591             const uint8_t * r_192 = zero;
4592             const uint8_t * c_192 = zero;
4593             const uint8_t * r_256 = zero;
4594             const uint8_t * c_256 = zero;
4595             // verify P-256 OOB
4596             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
4597                 c_256 = connection->classic_oob_c_256;
4598                 if (connection->classic_oob_r_256 != NULL) {
4599                     r_256 = connection->classic_oob_r_256;
4600                 }
4601             }
4602             // verify P-192 OOB
4603             if ((connection->classic_oob_c_192 != NULL)) {
4604                 c_192 = connection->classic_oob_c_192;
4605                 if (connection->classic_oob_r_192 != NULL) {
4606                     r_192 = connection->classic_oob_r_192;
4607                 }
4608             }
4609             // Reply
4610             if (c_256 != zero) {
4611                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
4612             } else if (c_192 != zero){
4613                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
4614             } else {
4615                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
4616             }
4617             return true;
4618         }
4619 #endif
4620 
4621         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
4622             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4623             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4624             return true;
4625         }
4626 
4627         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
4628             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4629             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
4630             return true;
4631         }
4632 
4633         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
4634             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4635             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4636             return true;
4637         }
4638 
4639         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4640             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
4641             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4642             return true;
4643         }
4644 
4645         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
4646             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
4647             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
4648             return true;
4649         }
4650 
4651         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
4652             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
4653             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
4654             return true;
4655         }
4656 
4657         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4658             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
4659             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
4660             connection->state = SENT_DISCONNECT;
4661             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4662             return true;
4663         }
4664 
4665         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
4666             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4667             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
4668             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4669             return true;
4670         }
4671 
4672         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4673             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4674             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4675             return true;
4676         }
4677         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4678             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4679             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4680             return true;
4681         }
4682 #endif
4683 
4684         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
4685             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
4686 #ifdef ENABLE_CLASSIC
4687             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
4688 #endif
4689             if (connection->state != SENT_DISCONNECT){
4690                 connection->state = SENT_DISCONNECT;
4691                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4692                 return true;
4693             }
4694         }
4695 
4696 #ifdef ENABLE_CLASSIC
4697         uint16_t sniff_min_interval;
4698         switch (connection->sniff_min_interval){
4699             case 0:
4700                 break;
4701             case 0xffff:
4702                 connection->sniff_min_interval = 0;
4703                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4704                 return true;
4705             default:
4706                 sniff_min_interval = connection->sniff_min_interval;
4707                 connection->sniff_min_interval = 0;
4708                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4709                 return true;
4710         }
4711 
4712         if (connection->sniff_subrating_max_latency != 0xffff){
4713             uint16_t max_latency = connection->sniff_subrating_max_latency;
4714             connection->sniff_subrating_max_latency = 0;
4715             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
4716             return true;
4717         }
4718 
4719         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
4720             uint8_t service_type = (uint8_t) connection->qos_service_type;
4721             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
4722             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);
4723             return true;
4724         }
4725 
4726         if (connection->request_role != HCI_ROLE_INVALID){
4727             hci_role_t role = connection->request_role;
4728             connection->request_role = HCI_ROLE_INVALID;
4729             hci_send_cmd(&hci_switch_role_command, connection->address, role);
4730             return true;
4731         }
4732 #endif
4733 
4734 #ifdef ENABLE_BLE
4735         switch (connection->le_con_parameter_update_state){
4736             // response to L2CAP CON PARAMETER UPDATE REQUEST
4737             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4738                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4739                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4740                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4741                              0x0000, 0xffff);
4742                 return true;
4743             case CON_PARAMETER_UPDATE_REPLY:
4744                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4745                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
4746                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4747                              0x0000, 0xffff);
4748                 return true;
4749             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
4750                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4751                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4752                 return true;
4753             default:
4754                 break;
4755         }
4756         if (connection->le_phy_update_all_phys != 0xffu){
4757             uint8_t all_phys = connection->le_phy_update_all_phys;
4758             connection->le_phy_update_all_phys = 0xff;
4759             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);
4760             return true;
4761         }
4762 #endif
4763     }
4764     return false;
4765 }
4766 
4767 static void hci_run(void){
4768 
4769     bool done;
4770 
4771     // send continuation fragments first, as they block the prepared packet buffer
4772     done = hci_run_acl_fragments();
4773     if (done) return;
4774 
4775 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4776     // send host num completed packets next as they don't require num_cmd_packets > 0
4777     if (!hci_can_send_comand_packet_transport()) return;
4778     if (hci_stack->host_completed_packets){
4779         hci_host_num_completed_packets();
4780         return;
4781     }
4782 #endif
4783 
4784     if (!hci_can_send_command_packet_now()) return;
4785 
4786     // global/non-connection oriented commands
4787 
4788 
4789 #ifdef ENABLE_CLASSIC
4790     // general gap classic
4791     done = hci_run_general_gap_classic();
4792     if (done) return;
4793 #endif
4794 
4795 #ifdef ENABLE_BLE
4796     // general gap le
4797     done = hci_run_general_gap_le();
4798     if (done) return;
4799 #endif
4800 
4801     // send pending HCI commands
4802     done = hci_run_general_pending_commands();
4803     if (done) return;
4804 
4805     // stack state sub statemachines
4806     hci_connection_t * connection;
4807     switch (hci_stack->state){
4808         case HCI_STATE_INITIALIZING:
4809             hci_initializing_run();
4810             break;
4811 
4812         case HCI_STATE_HALTING:
4813 
4814             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4815             switch (hci_stack->substate){
4816                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
4817                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
4818 
4819 #ifdef ENABLE_BLE
4820 #ifdef ENABLE_LE_CENTRAL
4821                     // free whitelist entries
4822                     {
4823                         btstack_linked_list_iterator_t lit;
4824                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4825                         while (btstack_linked_list_iterator_has_next(&lit)){
4826                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4827                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4828                             btstack_memory_whitelist_entry_free(entry);
4829                         }
4830                     }
4831 #endif
4832 #endif
4833                     // close all open connections
4834                     connection =  (hci_connection_t *) hci_stack->connections;
4835                     if (connection){
4836                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4837                         if (!hci_can_send_command_packet_now()) return;
4838 
4839                         // check state
4840                         if (connection->state == SENT_DISCONNECT) return;
4841                         connection->state = SENT_DISCONNECT;
4842 
4843                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4844 
4845                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
4846                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
4847 
4848                         // ... which would be ignored anyway as we shutdown (free) the connection now
4849                         hci_shutdown_connection(connection);
4850 
4851                         // finally, send the disconnect command
4852                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4853                         return;
4854                     }
4855 
4856                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
4857                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4858                         log_info("HCI_STATE_HALTING: wait 50 ms");
4859                         hci_stack->substate = HCI_HALTING_W4_TIMER;
4860                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4861                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4862                         btstack_run_loop_add_timer(&hci_stack->timeout);
4863                         break;
4864                     }
4865 
4866                     /* fall through */
4867 
4868                 case HCI_HALTING_CLOSE:
4869                     log_info("HCI_STATE_HALTING, calling off");
4870 
4871                     // switch mode
4872                     hci_power_control_off();
4873 
4874                     log_info("HCI_STATE_HALTING, emitting state");
4875                     hci_emit_state();
4876                     log_info("HCI_STATE_HALTING, done");
4877                     break;
4878 
4879                 case HCI_HALTING_W4_TIMER:
4880                     // keep waiting
4881 
4882                     break;
4883                 default:
4884                     break;
4885             }
4886 
4887             break;
4888 
4889         case HCI_STATE_FALLING_ASLEEP:
4890             switch(hci_stack->substate) {
4891                 case HCI_FALLING_ASLEEP_DISCONNECT:
4892                     log_info("HCI_STATE_FALLING_ASLEEP");
4893                     // close all open connections
4894                     connection =  (hci_connection_t *) hci_stack->connections;
4895 
4896 #ifdef HAVE_PLATFORM_IPHONE_OS
4897                     // don't close connections, if H4 supports power management
4898                     if (btstack_control_iphone_power_management_enabled()){
4899                         connection = NULL;
4900                     }
4901 #endif
4902                     if (connection){
4903 
4904                         // send disconnect
4905                         if (!hci_can_send_command_packet_now()) return;
4906 
4907                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
4908                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4909 
4910                         // send disconnected event right away - causes higher layer connections to get closed, too.
4911                         hci_shutdown_connection(connection);
4912                         return;
4913                     }
4914 
4915                     if (hci_classic_supported()){
4916                         // disable page and inquiry scan
4917                         if (!hci_can_send_command_packet_now()) return;
4918 
4919                         log_info("HCI_STATE_HALTING, disabling inq scans");
4920                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
4921 
4922                         // continue in next sub state
4923                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
4924                         break;
4925                     }
4926 
4927                     /* fall through */
4928 
4929                 case HCI_FALLING_ASLEEP_COMPLETE:
4930                     log_info("HCI_STATE_HALTING, calling sleep");
4931 #ifdef HAVE_PLATFORM_IPHONE_OS
4932                     // don't actually go to sleep, if H4 supports power management
4933                     if (btstack_control_iphone_power_management_enabled()){
4934                         // SLEEP MODE reached
4935                         hci_stack->state = HCI_STATE_SLEEPING;
4936                         hci_emit_state();
4937                         break;
4938                     }
4939 #endif
4940                     // switch mode
4941                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
4942                     hci_emit_state();
4943                     break;
4944 
4945                 default:
4946                     break;
4947             }
4948             break;
4949 
4950         default:
4951             break;
4952     }
4953 }
4954 
4955 int hci_send_cmd_packet(uint8_t *packet, int size){
4956     // house-keeping
4957 
4958 #ifdef ENABLE_CLASSIC
4959     bd_addr_t addr;
4960     hci_connection_t * conn;
4961 #endif
4962 #ifdef ENABLE_LE_CENTRAL
4963     uint8_t initiator_filter_policy;
4964 #endif
4965 
4966     uint16_t opcode = little_endian_read_16(packet, 0);
4967     switch (opcode) {
4968         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
4969             hci_stack->loopback_mode = packet[3];
4970             break;
4971 
4972 #ifdef ENABLE_CLASSIC
4973         case HCI_OPCODE_HCI_CREATE_CONNECTION:
4974             reverse_bd_addr(&packet[3], addr);
4975             log_info("Create_connection to %s", bd_addr_to_str(addr));
4976 
4977             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
4978             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
4979                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
4980                 return -1;
4981             }
4982 
4983             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4984             if (!conn) {
4985                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4986                 if (!conn) {
4987                     // notify client that alloc failed
4988                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4989                     return -1; // packet not sent to controller
4990                 }
4991                 conn->state = SEND_CREATE_CONNECTION;
4992                 conn->role  = HCI_ROLE_MASTER;
4993             }
4994             log_info("conn state %u", conn->state);
4995             switch (conn->state) {
4996                 // if connection active exists
4997                 case OPEN:
4998                     // and OPEN, emit connection complete command
4999                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
5000                     return -1; // packet not sent to controller
5001                 case RECEIVED_DISCONNECTION_COMPLETE:
5002                     // create connection triggered in disconnect complete event, let's do it now
5003                     break;
5004                 case SEND_CREATE_CONNECTION:
5005                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
5006                     break;
5007                 default:
5008                     // otherwise, just ignore as it is already in the open process
5009                     return -1; // packet not sent to controller
5010             }
5011             conn->state = SENT_CREATE_CONNECTION;
5012 
5013             // track outgoing connection
5014             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
5015             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
5016             break;
5017         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
5018             if (hci_stack->link_key_db) {
5019                 reverse_bd_addr(&packet[3], addr);
5020                 hci_stack->link_key_db->delete_link_key(addr);
5021             }
5022             break;
5023 
5024 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
5025         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5026             // setup_synchronous_connection? Voice setting at offset 22
5027             // TODO: compare to current setting if sco connection already active
5028             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
5029             break;
5030         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5031             // accept_synchronus_connection? Voice setting at offset 18
5032             // TODO: compare to current setting if sco connection already active
5033             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
5034             break;
5035 #endif
5036 #endif
5037 
5038 #ifdef ENABLE_BLE
5039         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
5040             hci_stack->le_random_address_set = 1;
5041             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
5042             break;
5043 #ifdef ENABLE_LE_PERIPHERAL
5044         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
5045             hci_stack->le_advertisements_active = packet[3] != 0;
5046             break;
5047 #endif
5048 #ifdef ENABLE_LE_CENTRAL
5049         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5050             // white list used?
5051             initiator_filter_policy = packet[7];
5052             switch (initiator_filter_policy) {
5053                 case 0:
5054                     // whitelist not used
5055                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
5056                     break;
5057                 case 1:
5058                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
5059                     break;
5060                 default:
5061                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
5062                     break;
5063             }
5064             // track outgoing connection
5065             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
5066             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
5067             break;
5068         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
5069             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
5070             break;
5071 #endif
5072 #endif
5073         default:
5074             break;
5075     }
5076 
5077     hci_stack->num_cmd_packets--;
5078 
5079     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5080     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5081 }
5082 
5083 // disconnect because of security block
5084 void hci_disconnect_security_block(hci_con_handle_t con_handle){
5085     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5086     if (!connection) return;
5087     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
5088 }
5089 
5090 
5091 // Configure Secure Simple Pairing
5092 
5093 #ifdef ENABLE_CLASSIC
5094 
5095 // enable will enable SSP during init
5096 void gap_ssp_set_enable(int enable){
5097     hci_stack->ssp_enable = enable;
5098 }
5099 
5100 static int hci_local_ssp_activated(void){
5101     return gap_ssp_supported() && hci_stack->ssp_enable;
5102 }
5103 
5104 // if set, BTstack will respond to io capability request using authentication requirement
5105 void gap_ssp_set_io_capability(int io_capability){
5106     hci_stack->ssp_io_capability = io_capability;
5107 }
5108 void gap_ssp_set_authentication_requirement(int authentication_requirement){
5109     hci_stack->ssp_authentication_requirement = authentication_requirement;
5110 }
5111 
5112 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
5113 void gap_ssp_set_auto_accept(int auto_accept){
5114     hci_stack->ssp_auto_accept = auto_accept;
5115 }
5116 
5117 void gap_secure_connections_enable(bool enable){
5118     hci_stack->secure_connections_enable = enable;
5119 }
5120 
5121 #endif
5122 
5123 // va_list part of hci_send_cmd
5124 int hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
5125     if (!hci_can_send_command_packet_now()){
5126         log_error("hci_send_cmd called but cannot send packet now");
5127         return 0;
5128     }
5129 
5130     // for HCI INITIALIZATION
5131     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
5132     hci_stack->last_cmd_opcode = cmd->opcode;
5133 
5134     hci_reserve_packet_buffer();
5135     uint8_t * packet = hci_stack->hci_packet_buffer;
5136     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
5137     int err = hci_send_cmd_packet(packet, size);
5138 
5139     // release packet buffer on error or for synchronous transport implementations
5140     if ((err < 0) || hci_transport_synchronous()){
5141         hci_release_packet_buffer();
5142         hci_emit_transport_packet_sent();
5143     }
5144 
5145     return err;
5146 }
5147 
5148 /**
5149  * pre: numcmds >= 0 - it's allowed to send a command to the controller
5150  */
5151 int hci_send_cmd(const hci_cmd_t * cmd, ...){
5152     va_list argptr;
5153     va_start(argptr, cmd);
5154     int res = hci_send_cmd_va_arg(cmd, argptr);
5155     va_end(argptr);
5156     return res;
5157 }
5158 
5159 // Create various non-HCI events.
5160 // TODO: generalize, use table similar to hci_create_command
5161 
5162 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
5163     // dump packet
5164     if (dump) {
5165         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
5166     }
5167 
5168     // dispatch to all event handlers
5169     btstack_linked_list_iterator_t it;
5170     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
5171     while (btstack_linked_list_iterator_has_next(&it)){
5172         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
5173         entry->callback(HCI_EVENT_PACKET, 0, event, size);
5174     }
5175 }
5176 
5177 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
5178     if (!hci_stack->acl_packet_handler) return;
5179     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
5180 }
5181 
5182 #ifdef ENABLE_CLASSIC
5183 static void hci_notify_if_sco_can_send_now(void){
5184     // notify SCO sender if waiting
5185     if (!hci_stack->sco_waiting_for_can_send_now) return;
5186     if (hci_can_send_sco_packet_now()){
5187         hci_stack->sco_waiting_for_can_send_now = 0;
5188         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
5189         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
5190         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
5191     }
5192 }
5193 
5194 // parsing end emitting has been merged to reduce code size
5195 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
5196     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
5197 
5198     uint8_t * eir_data;
5199     ad_context_t context;
5200     const uint8_t * name;
5201     uint8_t         name_len;
5202 
5203     if (size < 3) return;
5204 
5205     int event_type = hci_event_packet_get_type(packet);
5206     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
5207     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
5208 
5209     switch (event_type){
5210         case HCI_EVENT_INQUIRY_RESULT:
5211         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5212             if (size != (3 + (num_responses * 14))) return;
5213             break;
5214         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5215             if (size != 257) return;
5216             if (num_responses != 1) return;
5217             break;
5218         default:
5219             return;
5220     }
5221 
5222     // event[1] is set at the end
5223     int i;
5224     for (i=0; i<num_responses;i++){
5225         memset(event, 0, sizeof(event));
5226         event[0] = GAP_EVENT_INQUIRY_RESULT;
5227         uint8_t event_size = 18;    // if name is not set by EIR
5228 
5229         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
5230         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
5231         (void)memcpy(&event[9],
5232                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
5233                      3); // class of device
5234         (void)memcpy(&event[12],
5235                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
5236                      2); // clock offset
5237 
5238         switch (event_type){
5239             case HCI_EVENT_INQUIRY_RESULT:
5240                 // 14,15,16,17 = 0, size 18
5241                 break;
5242             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5243                 event[14] = 1;
5244                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5245                 // 16,17 = 0, size 18
5246                 break;
5247             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5248                 event[14] = 1;
5249                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5250                 // EIR packets only contain a single inquiry response
5251                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
5252                 name = NULL;
5253                 // Iterate over EIR data
5254                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
5255                     uint8_t data_type    = ad_iterator_get_data_type(&context);
5256                     uint8_t data_size    = ad_iterator_get_data_len(&context);
5257                     const uint8_t * data = ad_iterator_get_data(&context);
5258                     // Prefer Complete Local Name over Shortened Local Name
5259                     switch (data_type){
5260                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
5261                             if (name) continue;
5262                             /* fall through */
5263                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
5264                             name = data;
5265                             name_len = data_size;
5266                             break;
5267                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
5268                             if (data_size != 8) break;
5269                             event[16] = 1;
5270                             memcpy(&event[17], data, 8);
5271                             break;
5272                         default:
5273                             break;
5274                     }
5275                 }
5276                 if (name){
5277                     event[25] = 1;
5278                     // truncate name if needed
5279                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
5280                     event[26] = len;
5281                     (void)memcpy(&event[27], name, len);
5282                     event_size += len;
5283                 }
5284                 break;
5285             default:
5286                 return;
5287         }
5288         event[1] = event_size - 2;
5289         hci_emit_event(event, event_size, 1);
5290     }
5291 }
5292 #endif
5293 
5294 void hci_emit_state(void){
5295     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5296     uint8_t event[3];
5297     event[0] = BTSTACK_EVENT_STATE;
5298     event[1] = sizeof(event) - 2u;
5299     event[2] = hci_stack->state;
5300     hci_emit_event(event, sizeof(event), 1);
5301 }
5302 
5303 #ifdef ENABLE_CLASSIC
5304 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5305     uint8_t event[13];
5306     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5307     event[1] = sizeof(event) - 2;
5308     event[2] = status;
5309     little_endian_store_16(event, 3, con_handle);
5310     reverse_bd_addr(address, &event[5]);
5311     event[11] = 1; // ACL connection
5312     event[12] = 0; // encryption disabled
5313     hci_emit_event(event, sizeof(event), 1);
5314 }
5315 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
5316     if (disable_l2cap_timeouts) return;
5317     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
5318     uint8_t event[4];
5319     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
5320     event[1] = sizeof(event) - 2;
5321     little_endian_store_16(event, 2, conn->con_handle);
5322     hci_emit_event(event, sizeof(event), 1);
5323 }
5324 #endif
5325 
5326 #ifdef ENABLE_BLE
5327 #ifdef ENABLE_LE_CENTRAL
5328 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){
5329     uint8_t event[21];
5330     event[0] = HCI_EVENT_LE_META;
5331     event[1] = sizeof(event) - 2u;
5332     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
5333     event[3] = status;
5334     little_endian_store_16(event, 4, con_handle);
5335     event[6] = 0; // TODO: role
5336     event[7] = address_type;
5337     reverse_bd_addr(address, &event[8]);
5338     little_endian_store_16(event, 14, 0); // interval
5339     little_endian_store_16(event, 16, 0); // latency
5340     little_endian_store_16(event, 18, 0); // supervision timeout
5341     event[20] = 0; // master clock accuracy
5342     hci_emit_event(event, sizeof(event), 1);
5343 }
5344 #endif
5345 #endif
5346 
5347 static void hci_emit_transport_packet_sent(void){
5348     // notify upper stack that it might be possible to send again
5349     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5350     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5351 }
5352 
5353 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5354     uint8_t event[6];
5355     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
5356     event[1] = sizeof(event) - 2u;
5357     event[2] = 0; // status = OK
5358     little_endian_store_16(event, 3, con_handle);
5359     event[5] = reason;
5360     hci_emit_event(event, sizeof(event), 1);
5361 }
5362 
5363 static void hci_emit_nr_connections_changed(void){
5364     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5365     uint8_t event[3];
5366     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
5367     event[1] = sizeof(event) - 2u;
5368     event[2] = nr_hci_connections();
5369     hci_emit_event(event, sizeof(event), 1);
5370 }
5371 
5372 static void hci_emit_hci_open_failed(void){
5373     log_info("BTSTACK_EVENT_POWERON_FAILED");
5374     uint8_t event[2];
5375     event[0] = BTSTACK_EVENT_POWERON_FAILED;
5376     event[1] = sizeof(event) - 2u;
5377     hci_emit_event(event, sizeof(event), 1);
5378 }
5379 
5380 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
5381     log_info("hci_emit_dedicated_bonding_result %u ", status);
5382     uint8_t event[9];
5383     int pos = 0;
5384     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
5385     event[pos++] = sizeof(event) - 2u;
5386     event[pos++] = status;
5387     reverse_bd_addr(address, &event[pos]);
5388     hci_emit_event(event, sizeof(event), 1);
5389 }
5390 
5391 
5392 #ifdef ENABLE_CLASSIC
5393 
5394 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5395     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5396     uint8_t event[5];
5397     int pos = 0;
5398     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5399     event[pos++] = sizeof(event) - 2;
5400     little_endian_store_16(event, 2, con_handle);
5401     pos += 2;
5402     event[pos++] = level;
5403     hci_emit_event(event, sizeof(event), 1);
5404 }
5405 
5406 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
5407     if (!connection) return LEVEL_0;
5408     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5409     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
5410     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5411     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
5412     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5413     // LEVEL 4 always requires 128 bit encrytion key size
5414     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5415         security_level = LEVEL_3;
5416     }
5417     return security_level;
5418 }
5419 
5420 static void hci_emit_discoverable_enabled(uint8_t enabled){
5421     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
5422     uint8_t event[3];
5423     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
5424     event[1] = sizeof(event) - 2;
5425     event[2] = enabled;
5426     hci_emit_event(event, sizeof(event), 1);
5427 }
5428 
5429 // query if remote side supports eSCO
5430 int hci_remote_esco_supported(hci_con_handle_t con_handle){
5431     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5432     if (!connection) return 0;
5433     return (connection->remote_supported_features[0] & 1) != 0;
5434 }
5435 
5436 static bool hci_ssp_supported(hci_connection_t * connection){
5437     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
5438     return (connection->bonding_flags & mask) == mask;
5439 }
5440 
5441 // query if remote side supports SSP
5442 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
5443     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5444     if (!connection) return 0;
5445     return hci_ssp_supported(connection) ? 1 : 0;
5446 }
5447 
5448 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5449     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5450 }
5451 
5452 // GAP API
5453 /**
5454  * @bbrief enable/disable bonding. default is enabled
5455  * @praram enabled
5456  */
5457 void gap_set_bondable_mode(int enable){
5458     hci_stack->bondable = enable ? 1 : 0;
5459 }
5460 /**
5461  * @brief Get bondable mode.
5462  * @return 1 if bondable
5463  */
5464 int gap_get_bondable_mode(void){
5465     return hci_stack->bondable;
5466 }
5467 
5468 /**
5469  * @brief map link keys to security levels
5470  */
5471 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
5472     switch (link_key_type){
5473         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5474             return LEVEL_4;
5475         case COMBINATION_KEY:
5476         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5477             return LEVEL_3;
5478         default:
5479             return LEVEL_2;
5480     }
5481 }
5482 
5483 /**
5484  * @brief map link keys to secure connection yes/no
5485  */
5486 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
5487     switch (link_key_type){
5488         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5489         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5490             return 1;
5491         default:
5492             return 0;
5493     }
5494 }
5495 
5496 /**
5497  * @brief map link keys to authenticated
5498  */
5499 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
5500     switch (link_key_type){
5501         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5502         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5503             return 1;
5504         default:
5505             return 0;
5506     }
5507 }
5508 
5509 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
5510     log_info("gap_mitm_protection_required_for_security_level %u", level);
5511     return level > LEVEL_2;
5512 }
5513 
5514 /**
5515  * @brief get current security level
5516  */
5517 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
5518     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5519     if (!connection) return LEVEL_0;
5520     return gap_security_level_for_connection(connection);
5521 }
5522 
5523 /**
5524  * @brief request connection to device to
5525  * @result GAP_AUTHENTICATION_RESULT
5526  */
5527 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
5528     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5529     if (!connection){
5530         hci_emit_security_level(con_handle, LEVEL_0);
5531         return;
5532     }
5533 
5534     btstack_assert(hci_is_le_connection(connection) == false);
5535 
5536     // 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)
5537     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
5538     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
5539         requested_level = LEVEL_4;
5540     }
5541 
5542     gap_security_level_t current_level = gap_security_level(con_handle);
5543     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
5544         requested_level, connection->requested_security_level, current_level);
5545 
5546     // authentication active if authentication request was sent or planned level > 0
5547     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
5548     if (authentication_active){
5549         // authentication already active
5550         if (connection->requested_security_level < requested_level){
5551             // increase requested level as new level is higher
5552             // TODO: handle re-authentication when done
5553             connection->requested_security_level = requested_level;
5554         }
5555     } else {
5556         // no request active, notify if security sufficient
5557         if (requested_level <= current_level){
5558             hci_emit_security_level(con_handle, current_level);
5559             return;
5560         }
5561 
5562         // store request
5563         connection->requested_security_level = requested_level;
5564 
5565         // start to authenticate connection
5566         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5567         hci_run();
5568     }
5569 }
5570 
5571 /**
5572  * @brief start dedicated bonding with device. disconnect after bonding
5573  * @param device
5574  * @param request MITM protection
5575  * @result GAP_DEDICATED_BONDING_COMPLETE
5576  */
5577 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5578 
5579     // create connection state machine
5580     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5581 
5582     if (!connection){
5583         return BTSTACK_MEMORY_ALLOC_FAILED;
5584     }
5585 
5586     // delete linkn key
5587     gap_drop_link_key_for_bd_addr(device);
5588 
5589     // configure LEVEL_2/3, dedicated bonding
5590     connection->state = SEND_CREATE_CONNECTION;
5591     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5592     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5593     connection->bonding_flags = BONDING_DEDICATED;
5594 
5595     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5596 
5597     // handle: connnection failure (connection complete != ok)
5598     // handle: authentication failure
5599     // handle: disconnect on done
5600 
5601     hci_run();
5602 
5603     return 0;
5604 }
5605 #endif
5606 
5607 void gap_set_local_name(const char * local_name){
5608     hci_stack->local_name = local_name;
5609 }
5610 
5611 
5612 #ifdef ENABLE_BLE
5613 
5614 #ifdef ENABLE_LE_CENTRAL
5615 void gap_start_scan(void){
5616     hci_stack->le_scanning_enabled = true;
5617     hci_run();
5618 }
5619 
5620 void gap_stop_scan(void){
5621     hci_stack->le_scanning_enabled = false;
5622     hci_run();
5623 }
5624 
5625 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5626     hci_stack->le_scan_type          = scan_type;
5627     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5628     hci_stack->le_scan_interval      = scan_interval;
5629     hci_stack->le_scan_window        = scan_window;
5630     hci_stack->le_scanning_param_update = true;
5631     hci_run();
5632 }
5633 
5634 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5635     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5636 }
5637 
5638 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
5639     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
5640     if (!conn){
5641         // disallow if le connection is already outgoing
5642         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5643             log_error("le connection already active");
5644             return ERROR_CODE_COMMAND_DISALLOWED;
5645         }
5646 
5647         log_info("gap_connect: no connection exists yet, creating context");
5648         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
5649         if (!conn){
5650             // notify client that alloc failed
5651             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5652             log_info("gap_connect: failed to alloc hci_connection_t");
5653             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
5654         }
5655 
5656         // set le connecting state
5657         if (hci_is_le_connection_type(addr_type)){
5658             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5659         }
5660 
5661         conn->state = SEND_CREATE_CONNECTION;
5662         log_info("gap_connect: send create connection next");
5663         hci_run();
5664         return ERROR_CODE_SUCCESS;
5665     }
5666 
5667     if (!hci_is_le_connection(conn) ||
5668         (conn->state == SEND_CREATE_CONNECTION) ||
5669         (conn->state == SENT_CREATE_CONNECTION)) {
5670         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5671         log_error("gap_connect: classic connection or connect is already being created");
5672         return GATT_CLIENT_IN_WRONG_STATE;
5673     }
5674 
5675     // check if connection was just disconnected
5676     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5677         log_info("gap_connect: send create connection (again)");
5678         conn->state = SEND_CREATE_CONNECTION;
5679         hci_run();
5680         return ERROR_CODE_SUCCESS;
5681     }
5682 
5683     log_info("gap_connect: context exists with state %u", conn->state);
5684     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
5685     hci_run();
5686     return ERROR_CODE_SUCCESS;
5687 }
5688 
5689 // @assumption: only a single outgoing LE Connection exists
5690 static hci_connection_t * gap_get_outgoing_connection(void){
5691     btstack_linked_item_t *it;
5692     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5693         hci_connection_t * conn = (hci_connection_t *) it;
5694         if (!hci_is_le_connection(conn)) continue;
5695         switch (conn->state){
5696             case SEND_CREATE_CONNECTION:
5697             case SENT_CREATE_CONNECTION:
5698             case SENT_CANCEL_CONNECTION:
5699                 return conn;
5700             default:
5701                 break;
5702         };
5703     }
5704     return NULL;
5705 }
5706 
5707 uint8_t gap_connect_cancel(void){
5708     hci_connection_t * conn = gap_get_outgoing_connection();
5709     if (!conn) return 0;
5710     switch (conn->state){
5711         case SEND_CREATE_CONNECTION:
5712             // skip sending create connection and emit event instead
5713             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5714             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5715             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
5716             btstack_memory_hci_connection_free( conn );
5717             break;
5718         case SENT_CREATE_CONNECTION:
5719             // request to send cancel connection
5720             conn->state = SEND_CANCEL_CONNECTION;
5721             hci_run();
5722             break;
5723         default:
5724             break;
5725     }
5726     return 0;
5727 }
5728 #endif
5729 
5730 #ifdef ENABLE_LE_CENTRAL
5731 /**
5732  * @brief Set connection parameters for outgoing connections
5733  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5734  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
5735  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
5736  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
5737  * @param conn_latency, default: 4
5738  * @param supervision_timeout (unit: 10ms), default: 720 ms
5739  * @param min_ce_length (unit: 0.625ms), default: 10 ms
5740  * @param max_ce_length (unit: 0.625ms), default: 30 ms
5741  */
5742 
5743 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5744     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5745     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5746     hci_stack->le_connection_scan_interval = conn_scan_interval;
5747     hci_stack->le_connection_scan_window = conn_scan_window;
5748     hci_stack->le_connection_interval_min = conn_interval_min;
5749     hci_stack->le_connection_interval_max = conn_interval_max;
5750     hci_stack->le_connection_latency = conn_latency;
5751     hci_stack->le_supervision_timeout = supervision_timeout;
5752     hci_stack->le_minimum_ce_length = min_ce_length;
5753     hci_stack->le_maximum_ce_length = max_ce_length;
5754 }
5755 #endif
5756 
5757 /**
5758  * @brief Updates the connection parameters for a given LE connection
5759  * @param handle
5760  * @param conn_interval_min (unit: 1.25ms)
5761  * @param conn_interval_max (unit: 1.25ms)
5762  * @param conn_latency
5763  * @param supervision_timeout (unit: 10ms)
5764  * @returns 0 if ok
5765  */
5766 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5767     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5768     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5769     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5770     connection->le_conn_interval_min = conn_interval_min;
5771     connection->le_conn_interval_max = conn_interval_max;
5772     connection->le_conn_latency = conn_latency;
5773     connection->le_supervision_timeout = supervision_timeout;
5774     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
5775     hci_run();
5776     return 0;
5777 }
5778 
5779 /**
5780  * @brief Request an update of the connection parameter for a given LE connection
5781  * @param handle
5782  * @param conn_interval_min (unit: 1.25ms)
5783  * @param conn_interval_max (unit: 1.25ms)
5784  * @param conn_latency
5785  * @param supervision_timeout (unit: 10ms)
5786  * @returns 0 if ok
5787  */
5788 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5789     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5790     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5791     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5792     connection->le_conn_interval_min = conn_interval_min;
5793     connection->le_conn_interval_max = conn_interval_max;
5794     connection->le_conn_latency = conn_latency;
5795     connection->le_supervision_timeout = supervision_timeout;
5796     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
5797     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
5798     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
5799     return 0;
5800 }
5801 
5802 #ifdef ENABLE_LE_PERIPHERAL
5803 
5804 /**
5805  * @brief Set Advertisement Data
5806  * @param advertising_data_length
5807  * @param advertising_data (max 31 octets)
5808  * @note data is not copied, pointer has to stay valid
5809  */
5810 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
5811     hci_stack->le_advertisements_data_len = advertising_data_length;
5812     hci_stack->le_advertisements_data = advertising_data;
5813     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5814     hci_run();
5815 }
5816 
5817 /**
5818  * @brief Set Scan Response Data
5819  * @param advertising_data_length
5820  * @param advertising_data (max 31 octets)
5821  * @note data is not copied, pointer has to stay valid
5822  */
5823 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
5824     hci_stack->le_scan_response_data_len = scan_response_data_length;
5825     hci_stack->le_scan_response_data = scan_response_data;
5826     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5827     hci_run();
5828 }
5829 
5830 /**
5831  * @brief Set Advertisement Parameters
5832  * @param adv_int_min
5833  * @param adv_int_max
5834  * @param adv_type
5835  * @param direct_address_type
5836  * @param direct_address
5837  * @param channel_map
5838  * @param filter_policy
5839  *
5840  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
5841  */
5842  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
5843     uint8_t direct_address_typ, bd_addr_t direct_address,
5844     uint8_t channel_map, uint8_t filter_policy) {
5845 
5846     hci_stack->le_advertisements_interval_min = adv_int_min;
5847     hci_stack->le_advertisements_interval_max = adv_int_max;
5848     hci_stack->le_advertisements_type = adv_type;
5849     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
5850     hci_stack->le_advertisements_channel_map = channel_map;
5851     hci_stack->le_advertisements_filter_policy = filter_policy;
5852     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
5853                  6);
5854 
5855     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_PARAMS_SET;
5856     hci_run();
5857  }
5858 
5859 /**
5860  * @brief Enable/Disable Advertisements
5861  * @param enabled
5862  */
5863 void gap_advertisements_enable(int enabled){
5864     hci_stack->le_advertisements_enabled = enabled != 0;
5865     hci_update_advertisements_enabled_for_current_roles();
5866     hci_run();
5867 }
5868 
5869 #endif
5870 
5871 void hci_le_set_own_address_type(uint8_t own_address_type){
5872     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
5873     if (own_address_type == hci_stack->le_own_addr_type) return;
5874     hci_stack->le_own_addr_type = own_address_type;
5875 
5876 #ifdef ENABLE_LE_PERIPHERAL
5877     // update advertisement parameters, too
5878     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5879     hci_run();
5880 #endif
5881 #ifdef ENABLE_LE_CENTRAL
5882     // note: we don't update scan parameters or modify ongoing connection attempts
5883 #endif
5884 }
5885 
5886 #endif
5887 
5888 uint8_t gap_disconnect(hci_con_handle_t handle){
5889     hci_connection_t * conn = hci_connection_for_handle(handle);
5890     if (!conn){
5891         hci_emit_disconnection_complete(handle, 0);
5892         return 0;
5893     }
5894     // ignore if already disconnected
5895     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5896         return 0;
5897     }
5898     conn->state = SEND_DISCONNECT;
5899     hci_run();
5900     return 0;
5901 }
5902 
5903 int gap_read_rssi(hci_con_handle_t con_handle){
5904     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5905     if (hci_connection == NULL) return 0;
5906     connectionSetAuthenticationFlags(hci_connection, AUTH_FLAG_READ_RSSI);
5907     hci_run();
5908     return 1;
5909 }
5910 
5911 /**
5912  * @brief Get connection type
5913  * @param con_handle
5914  * @result connection_type
5915  */
5916 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
5917     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5918     if (!conn) return GAP_CONNECTION_INVALID;
5919     switch (conn->address_type){
5920         case BD_ADDR_TYPE_LE_PUBLIC:
5921         case BD_ADDR_TYPE_LE_RANDOM:
5922             return GAP_CONNECTION_LE;
5923         case BD_ADDR_TYPE_SCO:
5924             return GAP_CONNECTION_SCO;
5925         case BD_ADDR_TYPE_ACL:
5926             return GAP_CONNECTION_ACL;
5927         default:
5928             return GAP_CONNECTION_INVALID;
5929     }
5930 }
5931 
5932 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
5933     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5934     if (!conn) return HCI_ROLE_INVALID;
5935     return (hci_role_t) conn->role;
5936 }
5937 
5938 
5939 #ifdef ENABLE_CLASSIC
5940 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
5941     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5942     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5943     conn->request_role = role;
5944     hci_run();
5945     return ERROR_CODE_SUCCESS;
5946 }
5947 #endif
5948 
5949 #ifdef ENABLE_BLE
5950 
5951 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){
5952     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5953     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5954 
5955     conn->le_phy_update_all_phys    = all_phys;
5956     conn->le_phy_update_tx_phys     = tx_phys;
5957     conn->le_phy_update_rx_phys     = rx_phys;
5958     conn->le_phy_update_phy_options = phy_options;
5959 
5960     hci_run();
5961 
5962     return 0;
5963 }
5964 
5965 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
5966     // check if already in list
5967     btstack_linked_list_iterator_t it;
5968     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5969     while (btstack_linked_list_iterator_has_next(&it)) {
5970         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
5971         if (entry->address_type != address_type) {
5972             continue;
5973         }
5974         if (memcmp(entry->address, address, 6) != 0) {
5975             continue;
5976         }
5977 		// disallow if already scheduled to add
5978 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
5979 			return ERROR_CODE_COMMAND_DISALLOWED;
5980 		}
5981 		// still on controller, but scheduled to remove -> re-add
5982 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
5983 		return ERROR_CODE_SUCCESS;
5984     }
5985     // alloc and add to list
5986     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
5987     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
5988     entry->address_type = address_type;
5989     (void)memcpy(entry->address, address, 6);
5990     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5991     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
5992     return ERROR_CODE_SUCCESS;
5993 }
5994 
5995 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
5996     btstack_linked_list_iterator_t it;
5997     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5998     while (btstack_linked_list_iterator_has_next(&it)){
5999         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6000         if (entry->address_type != address_type) {
6001             continue;
6002         }
6003         if (memcmp(entry->address, address, 6) != 0) {
6004             continue;
6005         }
6006         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6007             // remove from controller if already present
6008             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6009         }  else {
6010             // directly remove entry from whitelist
6011             btstack_linked_list_iterator_remove(&it);
6012             btstack_memory_whitelist_entry_free(entry);
6013         }
6014         return ERROR_CODE_SUCCESS;
6015     }
6016     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6017 }
6018 
6019 static void hci_whitelist_clear(void){
6020     btstack_linked_list_iterator_t it;
6021     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6022     while (btstack_linked_list_iterator_has_next(&it)){
6023         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6024         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6025             // remove from controller if already present
6026             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6027             continue;
6028         }
6029         // directly remove entry from whitelist
6030         btstack_linked_list_iterator_remove(&it);
6031         btstack_memory_whitelist_entry_free(entry);
6032     }
6033 }
6034 
6035 /**
6036  * @brief Clear Whitelist
6037  * @returns 0 if ok
6038  */
6039 uint8_t gap_whitelist_clear(void){
6040     hci_whitelist_clear();
6041     hci_run();
6042     return ERROR_CODE_SUCCESS;
6043 }
6044 
6045 /**
6046  * @brief Add Device to Whitelist
6047  * @param address_typ
6048  * @param address
6049  * @returns 0 if ok
6050  */
6051 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6052     uint8_t status = hci_whitelist_add(address_type, address);
6053     if (status){
6054         return status;
6055     }
6056     hci_run();
6057     return ERROR_CODE_SUCCESS;
6058 }
6059 
6060 /**
6061  * @brief Remove Device from Whitelist
6062  * @param address_typ
6063  * @param address
6064  * @returns 0 if ok
6065  */
6066 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6067     uint8_t status = hci_whitelist_remove(address_type, address);
6068     if (status){
6069         return status;
6070     }
6071     hci_run();
6072     return ERROR_CODE_SUCCESS;
6073 }
6074 
6075 #ifdef ENABLE_LE_CENTRAL
6076 /**
6077  *  @brief Connect with Whitelist
6078  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
6079  *  @returns - if ok
6080  */
6081 uint8_t gap_connect_with_whitelist(void){
6082     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6083         return ERROR_CODE_COMMAND_DISALLOWED;
6084     }
6085     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6086     hci_run();
6087     return ERROR_CODE_SUCCESS;
6088 }
6089 
6090 /**
6091  * @brief Auto Connection Establishment - Start Connecting to device
6092  * @param address_typ
6093  * @param address
6094  * @returns 0 if ok
6095  */
6096 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
6097     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6098         return ERROR_CODE_COMMAND_DISALLOWED;
6099     }
6100 
6101     uint8_t status = hci_whitelist_add(address_type, address);
6102     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
6103         return status;
6104     }
6105 
6106     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6107 
6108     hci_run();
6109     return ERROR_CODE_SUCCESS;
6110 }
6111 
6112 /**
6113  * @brief Auto Connection Establishment - Stop Connecting to device
6114  * @param address_typ
6115  * @param address
6116  * @returns 0 if ok
6117  */
6118 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
6119     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6120         return ERROR_CODE_COMMAND_DISALLOWED;
6121     }
6122 
6123     hci_whitelist_remove(address_type, address);
6124     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
6125         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6126     }
6127     hci_run();
6128     return 0;
6129 }
6130 
6131 /**
6132  * @brief Auto Connection Establishment - Stop everything
6133  * @note  Convenience function to stop all active auto connection attempts
6134  */
6135 uint8_t gap_auto_connection_stop_all(void){
6136     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
6137         return ERROR_CODE_COMMAND_DISALLOWED;
6138     }
6139     hci_whitelist_clear();
6140     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6141     hci_run();
6142     return ERROR_CODE_SUCCESS;
6143 }
6144 
6145 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
6146     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6147     if (!conn) return 0;
6148     return conn->le_connection_interval;
6149 }
6150 #endif
6151 #endif
6152 
6153 #ifdef ENABLE_CLASSIC
6154 /**
6155  * @brief Set Extended Inquiry Response data
6156  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
6157  * @note has to be done before stack starts up
6158  */
6159 void gap_set_extended_inquiry_response(const uint8_t * data){
6160     hci_stack->eir_data = data;
6161 }
6162 
6163 /**
6164  * @brief Start GAP Classic Inquiry
6165  * @param duration in 1.28s units
6166  * @return 0 if ok
6167  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
6168  */
6169 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
6170     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
6171     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6172     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
6173         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
6174     }
6175     hci_stack->inquiry_state = duration_in_1280ms_units;
6176     hci_run();
6177     return 0;
6178 }
6179 
6180 /**
6181  * @brief Stop GAP Classic Inquiry
6182  * @returns 0 if ok
6183  */
6184 int gap_inquiry_stop(void){
6185     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
6186         // emit inquiry complete event, before it even started
6187         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
6188         hci_emit_event(event, sizeof(event), 1);
6189         return 0;
6190     }
6191     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
6192     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
6193     hci_run();
6194     return 0;
6195 }
6196 
6197 void gap_inquiry_set_lap(uint32_t lap){
6198     hci_stack->inquiry_lap = lap;
6199 }
6200 
6201 
6202 /**
6203  * @brief Remote Name Request
6204  * @param addr
6205  * @param page_scan_repetition_mode
6206  * @param clock_offset only used when bit 15 is set
6207  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
6208  */
6209 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
6210     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6211     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
6212     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
6213     hci_stack->remote_name_clock_offset = clock_offset;
6214     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
6215     hci_run();
6216     return 0;
6217 }
6218 
6219 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
6220     hci_stack->gap_pairing_state = state;
6221     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
6222     hci_run();
6223     return 0;
6224 }
6225 
6226 /**
6227  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
6228  * @param addr
6229  * @param pin_data
6230  * @param pin_len
6231  * @return 0 if ok
6232  */
6233 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
6234     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6235     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
6236     hci_stack->gap_pairing_pin_len = pin_len;
6237     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
6238 }
6239 
6240 /**
6241  * @brief Legacy Pairing Pin Code Response
6242  * @param addr
6243  * @param pin
6244  * @return 0 if ok
6245  */
6246 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
6247     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
6248 }
6249 
6250 /**
6251  * @brief Abort Legacy Pairing
6252  * @param addr
6253  * @param pin
6254  * @return 0 if ok
6255  */
6256 int gap_pin_code_negative(bd_addr_t addr){
6257     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6258     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
6259 }
6260 
6261 /**
6262  * @brief SSP Passkey Response
6263  * @param addr
6264  * @param passkey
6265  * @return 0 if ok
6266  */
6267 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
6268     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6269     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
6270     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
6271 }
6272 
6273 /**
6274  * @brief Abort SSP Passkey Entry/Pairing
6275  * @param addr
6276  * @param pin
6277  * @return 0 if ok
6278  */
6279 int gap_ssp_passkey_negative(const bd_addr_t addr){
6280     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6281     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
6282 }
6283 
6284 /**
6285  * @brief Accept SSP Numeric Comparison
6286  * @param addr
6287  * @param passkey
6288  * @return 0 if ok
6289  */
6290 int gap_ssp_confirmation_response(const bd_addr_t addr){
6291     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6292     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
6293 }
6294 
6295 /**
6296  * @brief Abort SSP Numeric Comparison/Pairing
6297  * @param addr
6298  * @param pin
6299  * @return 0 if ok
6300  */
6301 int gap_ssp_confirmation_negative(const bd_addr_t addr){
6302     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6303     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
6304 }
6305 
6306 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
6307 
6308 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
6309     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6310     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6311     connectionSetAuthenticationFlags(conn, flag);
6312     hci_run();
6313     return ERROR_CODE_SUCCESS;
6314 }
6315 
6316 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
6317     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_REPLY);
6318 }
6319 
6320 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
6321     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6322 }
6323 #endif
6324 
6325 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6326 /**
6327  * @brief Report Remote OOB Data
6328  * @param bd_addr
6329  * @param c_192 Simple Pairing Hash C derived from P-192 public key
6330  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
6331  * @param c_256 Simple Pairing Hash C derived from P-256 public key
6332  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
6333  */
6334 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){
6335     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6336     if (connection == NULL) {
6337         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6338     }
6339     connection->classic_oob_c_192 = c_192;
6340     connection->classic_oob_r_192 = r_192;
6341     connection->classic_oob_c_256 = c_256;
6342     connection->classic_oob_r_256 = r_256;
6343     return ERROR_CODE_SUCCESS;
6344 }
6345 /**
6346  * @brief Generate new OOB data
6347  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6348  */
6349 void gap_ssp_generate_oob_data(void){
6350     hci_stack->classic_read_local_oob_data = true;
6351     hci_run();
6352 }
6353 
6354 #endif
6355 
6356 /**
6357  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6358  * @param inquiry_mode see bluetooth_defines.h
6359  */
6360 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
6361     hci_stack->inquiry_mode = inquiry_mode;
6362 }
6363 
6364 /**
6365  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6366  */
6367 void hci_set_sco_voice_setting(uint16_t voice_setting){
6368     hci_stack->sco_voice_setting = voice_setting;
6369 }
6370 
6371 /**
6372  * @brief Get SCO Voice Setting
6373  * @return current voice setting
6374  */
6375 uint16_t hci_get_sco_voice_setting(void){
6376     return hci_stack->sco_voice_setting;
6377 }
6378 
6379 static int hci_have_usb_transport(void){
6380     if (!hci_stack->hci_transport) return 0;
6381     const char * transport_name = hci_stack->hci_transport->name;
6382     if (!transport_name) return 0;
6383     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6384 }
6385 
6386 /** @brief Get SCO packet length for current SCO Voice setting
6387  *  @note  Using SCO packets of the exact length is required for USB transfer
6388  *  @return Length of SCO packets in bytes (not audio frames)
6389  */
6390 int hci_get_sco_packet_length(void){
6391     int sco_packet_length = 0;
6392 
6393 #ifdef ENABLE_SCO_OVER_HCI
6394     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6395     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6396 
6397     if (hci_have_usb_transport()){
6398         // see Core Spec for H2 USB Transfer.
6399         // 3 byte SCO header + 24 bytes per connection
6400         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
6401         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6402     } else {
6403         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6404         sco_packet_length = 3 + 60 * multiplier;
6405         // assert that it still fits inside an SCO buffer
6406         if (sco_packet_length > hci_stack->sco_data_packet_length){
6407             sco_packet_length = 3 + 60;
6408         }
6409     }
6410 #endif
6411 
6412 #ifdef HAVE_SCO_TRANSPORT
6413     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6414     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6415     sco_packet_length = 3 + 60 * multiplier;
6416 #endif
6417     return sco_packet_length;
6418 }
6419 
6420 /**
6421 * @brief Sets the master/slave policy
6422 * @param policy (0: attempt to become master, 1: let connecting device decide)
6423 */
6424 void hci_set_master_slave_policy(uint8_t policy){
6425     hci_stack->master_slave_policy = policy;
6426 }
6427 
6428 #endif
6429 
6430 HCI_STATE hci_get_state(void){
6431     return hci_stack->state;
6432 }
6433 
6434 #ifdef ENABLE_CLASSIC
6435 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
6436     hci_stack->gap_classic_accept_callback = accept_callback;
6437 }
6438 #endif
6439 
6440 /**
6441  * @brief Set callback for Bluetooth Hardware Error
6442  */
6443 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6444     hci_stack->hardware_error_callback = fn;
6445 }
6446 
6447 void hci_disconnect_all(void){
6448     btstack_linked_list_iterator_t it;
6449     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6450     while (btstack_linked_list_iterator_has_next(&it)){
6451         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6452         if (con->state == SENT_DISCONNECT) continue;
6453         con->state = SEND_DISCONNECT;
6454     }
6455     hci_run();
6456 }
6457 
6458 uint16_t hci_get_manufacturer(void){
6459     return hci_stack->manufacturer;
6460 }
6461 
6462 #ifdef ENABLE_BLE
6463 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
6464     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
6465     if (!hci_con) return NULL;
6466     return &hci_con->sm_connection;
6467 }
6468 
6469 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
6470 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
6471 #endif
6472 
6473 int gap_encryption_key_size(hci_con_handle_t con_handle){
6474     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6475     if (hci_connection == NULL) return 0;
6476     if (hci_is_le_connection(hci_connection)){
6477 #ifdef ENABLE_BLE
6478         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6479         if (sm_conn->sm_connection_encrypted) {
6480             return sm_conn->sm_actual_encryption_key_size;
6481         }
6482 #endif
6483     } else {
6484 #ifdef ENABLE_CLASSIC
6485         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
6486             return hci_connection->encryption_key_size;
6487         }
6488 #endif
6489     }
6490     return 0;
6491 }
6492 
6493 int gap_authenticated(hci_con_handle_t con_handle){
6494     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6495     if (hci_connection == NULL) return 0;
6496 
6497     switch (hci_connection->address_type){
6498 #ifdef ENABLE_BLE
6499         case BD_ADDR_TYPE_LE_PUBLIC:
6500         case BD_ADDR_TYPE_LE_RANDOM:
6501             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6502             return hci_connection->sm_connection.sm_connection_authenticated;
6503 #endif
6504 #ifdef ENABLE_CLASSIC
6505         case BD_ADDR_TYPE_SCO:
6506         case BD_ADDR_TYPE_ACL:
6507             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
6508 #endif
6509         default:
6510             return 0;
6511     }
6512 }
6513 
6514 int gap_secure_connection(hci_con_handle_t con_handle){
6515     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6516     if (hci_connection == NULL) return 0;
6517 
6518     switch (hci_connection->address_type){
6519 #ifdef ENABLE_BLE
6520         case BD_ADDR_TYPE_LE_PUBLIC:
6521         case BD_ADDR_TYPE_LE_RANDOM:
6522             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6523             return hci_connection->sm_connection.sm_connection_sc;
6524 #endif
6525 #ifdef ENABLE_CLASSIC
6526         case BD_ADDR_TYPE_SCO:
6527         case BD_ADDR_TYPE_ACL:
6528             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
6529 #endif
6530         default:
6531             return 0;
6532     }
6533 }
6534 
6535 bool gap_bonded(hci_con_handle_t con_handle){
6536 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6537 	if (hci_connection == NULL) return 0;
6538 
6539 #ifdef ENABLE_CLASSIC
6540 	link_key_t link_key;
6541 	link_key_type_t link_key_type;
6542 #endif
6543 	switch (hci_connection->address_type){
6544 #ifdef ENABLE_BLE
6545 		case BD_ADDR_TYPE_LE_PUBLIC:
6546 		case BD_ADDR_TYPE_LE_RANDOM:
6547 			return hci_connection->sm_connection.sm_le_db_index >= 0;
6548 #endif
6549 #ifdef ENABLE_CLASSIC
6550 		case BD_ADDR_TYPE_SCO:
6551 		case BD_ADDR_TYPE_ACL:
6552 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
6553 #endif
6554 		default:
6555 			return false;
6556 	}
6557 }
6558 
6559 #ifdef ENABLE_BLE
6560 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
6561     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
6562     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
6563     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
6564     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
6565     return sm_conn->sm_connection_authorization_state;
6566 }
6567 #endif
6568 
6569 #ifdef ENABLE_CLASSIC
6570 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){
6571     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6572     if (!conn) return GAP_CONNECTION_INVALID;
6573     conn->sniff_min_interval = sniff_min_interval;
6574     conn->sniff_max_interval = sniff_max_interval;
6575     conn->sniff_attempt = sniff_attempt;
6576     conn->sniff_timeout = sniff_timeout;
6577     hci_run();
6578     return 0;
6579 }
6580 
6581 /**
6582  * @brief Exit Sniff mode
6583  * @param con_handle
6584  @ @return 0 if ok
6585  */
6586 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6587     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6588     if (!conn) return GAP_CONNECTION_INVALID;
6589     conn->sniff_min_interval = 0xffff;
6590     hci_run();
6591     return 0;
6592 }
6593 
6594 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){
6595     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6596     if (!conn) return GAP_CONNECTION_INVALID;
6597     conn->sniff_subrating_max_latency = max_latency;
6598     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
6599     conn->sniff_subrating_min_local_timeout = min_local_timeout;
6600     hci_run();
6601     return ERROR_CODE_SUCCESS;
6602 }
6603 
6604 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){
6605     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6606     if (!conn) return GAP_CONNECTION_INVALID;
6607     conn->qos_service_type = service_type;
6608     conn->qos_token_rate = token_rate;
6609     conn->qos_peak_bandwidth = peak_bandwidth;
6610     conn->qos_latency = latency;
6611     conn->qos_delay_variation = delay_variation;
6612     hci_run();
6613     return ERROR_CODE_SUCCESS;
6614 }
6615 
6616 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
6617     hci_stack->new_page_scan_interval = page_scan_interval;
6618     hci_stack->new_page_scan_window = page_scan_window;
6619     hci_run();
6620 }
6621 
6622 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
6623     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
6624     hci_run();
6625 }
6626 
6627 #endif
6628 
6629 void hci_halting_defer(void){
6630     if (hci_stack->state != HCI_STATE_HALTING) return;
6631     switch (hci_stack->substate){
6632         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6633         case HCI_HALTING_CLOSE:
6634             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6635             break;
6636         default:
6637             break;
6638     }
6639 }
6640 
6641 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6642 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
6643     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6644     if (le_device_db_index >= le_device_db_max_count()) return;
6645     uint8_t offset = le_device_db_index >> 3;
6646     uint8_t mask = 1 << (le_device_db_index & 7);
6647     hci_stack->le_resolving_list_add_entries[offset] |= mask;
6648     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6649     	// note: go back to remove entries, otherwise, a remove + add will skip the add
6650         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6651     }
6652 }
6653 
6654 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
6655 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6656 	if (le_device_db_index >= le_device_db_max_count()) return;
6657 	uint8_t offset = le_device_db_index >> 3;
6658 	uint8_t mask = 1 << (le_device_db_index & 7);
6659 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
6660 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6661 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6662 	}
6663 }
6664 
6665 uint8_t gap_load_resolving_list_from_le_device_db(void){
6666 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6667 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6668 	}
6669 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6670 		// restart le resolving list update
6671 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6672 	}
6673 	return ERROR_CODE_SUCCESS;
6674 }
6675 #endif
6676 
6677 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
6678 void hci_setup_test_connections_fuzz(void){
6679     hci_connection_t * conn;
6680 
6681     // default address: 66:55:44:33:00:01
6682     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
6683 
6684     // setup Controller info
6685     hci_stack->num_cmd_packets = 255;
6686     hci_stack->acl_packets_total_num = 255;
6687 
6688     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
6689     addr[5] = 0x01;
6690     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6691     conn->con_handle = addr[5];
6692     conn->role  = HCI_ROLE_SLAVE;
6693     conn->state = RECEIVED_CONNECTION_REQUEST;
6694     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6695 
6696     // setup incoming Classic SCO connection with con handle 0x0002
6697     addr[5] = 0x02;
6698     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6699     conn->con_handle = addr[5];
6700     conn->role  = HCI_ROLE_SLAVE;
6701     conn->state = RECEIVED_CONNECTION_REQUEST;
6702     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6703 
6704     // setup ready Classic ACL connection with con handle 0x0003
6705     addr[5] = 0x03;
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 = OPEN;
6710     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6711 
6712     // setup ready Classic SCO connection with con handle 0x0004
6713     addr[5] = 0x04;
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 = OPEN;
6718     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6719 
6720     // setup ready LE ACL connection with con handle 0x005 and public address
6721     addr[5] = 0x05;
6722     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
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     conn->sm_connection.sm_connection_encrypted = 1;
6728 }
6729 
6730 void hci_free_connections_fuzz(void){
6731     btstack_linked_list_iterator_t it;
6732     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6733     while (btstack_linked_list_iterator_has_next(&it)){
6734         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6735         btstack_linked_list_iterator_remove(&it);
6736         btstack_memory_hci_connection_free(con);
6737     }
6738 }
6739 void hci_simulate_working_fuzz(void){
6740     hci_init_done();
6741     hci_stack->num_cmd_packets = 255;
6742 }
6743 #endif
6744