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