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