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