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