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