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