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