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