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