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