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