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