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