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