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