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