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