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