xref: /btstack/src/hci.c (revision cb93c223bc3c718fbf6e414578af3369cbf3345f)
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_DEFAULT_LINK_POLICY_SETTING:
1354             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING;
1355             hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1356             break;
1357         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1358             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1359             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1360             break;
1361         case HCI_INIT_WRITE_LOCAL_NAME: {
1362             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1363             hci_reserve_packet_buffer();
1364             uint8_t * packet = hci_stack->hci_packet_buffer;
1365             // construct HCI Command and send
1366             uint16_t opcode = hci_write_local_name.opcode;
1367             hci_stack->last_cmd_opcode = opcode;
1368             packet[0] = opcode & 0xff;
1369             packet[1] = opcode >> 8;
1370             packet[2] = DEVICE_NAME_LEN;
1371             memset(&packet[3], 0, DEVICE_NAME_LEN);
1372             memcpy(&packet[3], hci_stack->local_name, strlen(hci_stack->local_name));
1373             // expand '00:00:00:00:00:00' in name with bd_addr
1374             hci_replace_bd_addr_placeholder(&packet[3], DEVICE_NAME_LEN);
1375             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1376             break;
1377         }
1378         case HCI_INIT_WRITE_EIR_DATA: {
1379             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1380             hci_reserve_packet_buffer();
1381             uint8_t * packet = hci_stack->hci_packet_buffer;
1382             // construct HCI Command and send
1383             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1384             hci_stack->last_cmd_opcode = opcode;
1385             packet[0] = opcode & 0xff;
1386             packet[1] = opcode >> 8;
1387             packet[2] = 1 + 240;
1388             packet[3] = 0;  // FEC not required
1389             if (hci_stack->eir_data){
1390                 memcpy(&packet[4], hci_stack->eir_data, 240);
1391             } else {
1392                 memset(&packet[4], 0, 240);
1393                 int name_len = strlen(hci_stack->local_name);
1394                 packet[4] = name_len + 1;
1395                 packet[5] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1396                 memcpy(&packet[6], hci_stack->local_name, name_len);
1397             }
1398             // expand '00:00:00:00:00:00' in name with bd_addr
1399             hci_replace_bd_addr_placeholder(&packet[4], 240);
1400             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + 240);
1401             break;
1402         }
1403         case HCI_INIT_WRITE_INQUIRY_MODE:
1404             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1405             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1406             break;
1407         case HCI_INIT_WRITE_SCAN_ENABLE:
1408             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1409             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1410             break;
1411         // only sent if ENABLE_SCO_OVER_HCI is defined
1412         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1413             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1414             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1415             break;
1416         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1417             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1418             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1419             break;
1420         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1421         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1422             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1423             log_info("BCM: Route SCO data via HCI transport");
1424             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1425             break;
1426 
1427 #endif
1428 #ifdef ENABLE_BLE
1429         // LE INIT
1430         case HCI_INIT_LE_READ_BUFFER_SIZE:
1431             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1432             hci_send_cmd(&hci_le_read_buffer_size);
1433             break;
1434         case HCI_INIT_LE_SET_EVENT_MASK:
1435             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1436             hci_send_cmd(&hci_le_set_event_mask, 0x1FF, 0x0);
1437             break;
1438         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1439             // LE Supported Host = 1, Simultaneous Host = 0
1440             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1441             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1442             break;
1443 #endif
1444 
1445 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1446         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1447             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1448             hci_send_cmd(&hci_le_read_maximum_data_length);
1449             break;
1450         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1451             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1452             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1453             break;
1454 #endif
1455 
1456 #ifdef ENABLE_LE_CENTRAL
1457         case HCI_INIT_READ_WHITE_LIST_SIZE:
1458             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1459             hci_send_cmd(&hci_le_read_white_list_size);
1460             break;
1461         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1462             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1463             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1464             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1465             break;
1466 #endif
1467         default:
1468             return;
1469     }
1470 }
1471 
1472 static void hci_init_done(void){
1473     // done. tell the app
1474     log_info("hci_init_done -> HCI_STATE_WORKING");
1475     hci_stack->state = HCI_STATE_WORKING;
1476     hci_emit_state();
1477     hci_run();
1478 }
1479 
1480 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1481 
1482     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
1483 
1484     uint8_t command_completed = 0;
1485 
1486     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1487         uint16_t opcode = little_endian_read_16(packet,3);
1488         if (opcode == hci_stack->last_cmd_opcode){
1489             command_completed = 1;
1490             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1491         } else {
1492             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1493         }
1494     }
1495 
1496     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1497         uint8_t  status = packet[2];
1498         uint16_t opcode = little_endian_read_16(packet,4);
1499         if (opcode == hci_stack->last_cmd_opcode){
1500             if (status){
1501                 command_completed = 1;
1502                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1503             } else {
1504                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1505             }
1506         } else {
1507             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1508         }
1509     }
1510 
1511 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1512 
1513     // Vendor == CSR
1514     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1515         // TODO: track actual command
1516         command_completed = 1;
1517     }
1518 
1519     // Vendor == Toshiba
1520     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1521         // TODO: track actual command
1522         command_completed = 1;
1523         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1524         hci_stack->num_cmd_packets = 1;
1525     }
1526 
1527     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1528     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1529     //
1530     // HCI Reset
1531     // Timeout 100 ms
1532     // HCI Reset
1533     // Command Complete Reset
1534     // HCI Read Local Version Information
1535     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1536     // hang...
1537     //
1538     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1539     if (!command_completed
1540             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1541             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1542 
1543         uint16_t opcode = little_endian_read_16(packet,3);
1544         if (opcode == hci_reset.opcode){
1545             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1546             return;
1547         }
1548     }
1549 
1550     // CSR & H5
1551     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1552     if (!command_completed
1553             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1554             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1555 
1556         uint16_t opcode = little_endian_read_16(packet,3);
1557         if (opcode == hci_reset.opcode){
1558             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1559             return;
1560         }
1561     }
1562 
1563     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1564     // fix: Correct substate and behave as command below
1565     if (command_completed){
1566         switch (hci_stack->substate){
1567             case HCI_INIT_SEND_RESET:
1568                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1569                 break;
1570             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1571                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1572                 break;
1573             default:
1574                 break;
1575         }
1576     }
1577 
1578 #endif
1579 
1580     if (!command_completed) return;
1581 
1582     int need_baud_change = 0;
1583     int need_addr_change = 0;
1584 
1585 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1586     need_baud_change = hci_stack->config
1587                         && hci_stack->chipset
1588                         && hci_stack->chipset->set_baudrate_command
1589                         && hci_stack->hci_transport->set_baudrate
1590                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1591 
1592     need_addr_change = hci_stack->custom_bd_addr_set
1593                         && hci_stack->chipset
1594                         && hci_stack->chipset->set_bd_addr_command;
1595 #endif
1596 
1597     switch(hci_stack->substate){
1598 
1599 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1600         case HCI_INIT_SEND_RESET:
1601             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1602             // fix: just correct substate and behave as command below
1603             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1604             btstack_run_loop_remove_timer(&hci_stack->timeout);
1605             break;
1606         case HCI_INIT_W4_SEND_RESET:
1607             btstack_run_loop_remove_timer(&hci_stack->timeout);
1608             break;
1609         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1610             log_info("Received local name, need baud change %d", need_baud_change);
1611             if (need_baud_change){
1612                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1613                 return;
1614             }
1615             // skip baud change
1616             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1617             return;
1618         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1619             // for STLC2500D, baud rate change already happened.
1620             // for others, baud rate gets changed now
1621             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1622                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1623                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1624                 hci_stack->hci_transport->set_baudrate(baud_rate);
1625             }
1626             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1627             return;
1628         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1629             btstack_run_loop_remove_timer(&hci_stack->timeout);
1630             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1631             return;
1632         case HCI_INIT_W4_CUSTOM_INIT:
1633             // repeat custom init
1634             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1635             return;
1636 #else
1637         case HCI_INIT_W4_SEND_RESET:
1638             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1639             return ;
1640 #endif
1641 
1642         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1643             if (need_baud_change &&
1644               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1645                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1646                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1647                 return;
1648             }
1649             if (need_addr_change){
1650                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1651                 return;
1652             }
1653             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1654             return;
1655 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1656         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1657             if (need_baud_change){
1658                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1659                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1660                 hci_stack->hci_transport->set_baudrate(baud_rate);
1661             }
1662             if (need_addr_change){
1663                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1664                 return;
1665             }
1666             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1667             return;
1668         case HCI_INIT_W4_SET_BD_ADDR:
1669             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1670             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1671             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1672                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1673                 return;
1674             }
1675             // skipping st warm boot
1676             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1677             return;
1678         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1679             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1680             return;
1681 #endif
1682         case HCI_INIT_W4_READ_BD_ADDR:
1683             // only read buffer size if supported
1684             if (hci_stack->local_supported_commands[0] & 0x01) {
1685                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1686                 return;
1687             }
1688             // skipping read buffer size
1689             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1690             return;
1691         case HCI_INIT_W4_SET_EVENT_MASK:
1692             // skip Classic init commands for LE only chipsets
1693             if (!hci_classic_supported()){
1694 #ifdef ENABLE_BLE
1695                 if (hci_le_supported()){
1696                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1697                     return;
1698                 }
1699 #endif
1700                 log_error("Neither BR/EDR nor LE supported");
1701                 hci_init_done();
1702                 return;
1703             }
1704             if (!gap_ssp_supported()){
1705                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1706                 return;
1707             }
1708             break;
1709 #ifdef ENABLE_BLE
1710         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1711             // skip write le host if not supported (e.g. on LE only EM9301)
1712             if (hci_stack->local_supported_commands[0] & 0x02) break;
1713             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1714             return;
1715 
1716 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1717         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1718             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
1719             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1720                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1721                 return;
1722             }
1723             // explicit fall through to reduce repetitions
1724 
1725 #ifdef ENABLE_LE_CENTRAL
1726             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1727 #else
1728             hci_init_done();
1729 #endif
1730             return;
1731 #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
1732 
1733 #endif  /* ENABLE_BLE */
1734 
1735 #ifdef ENABLE_SCO_OVER_HCI
1736         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1737             // skip write synchronous flow control if not supported
1738             if (hci_stack->local_supported_commands[0] & 0x04) break;
1739             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1740             // explicit fall through to reduce repetitions
1741 
1742         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1743             // skip write default erroneous data reporting if not supported
1744             if (hci_stack->local_supported_commands[0] & 0x08) break;
1745             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1746             // explicit fall through to reduce repetitions
1747 
1748         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1749             // skip bcm set sco pcm config on non-Broadcom chipsets
1750             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1751             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1752             // explicit fall through to reduce repetitions
1753 
1754         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1755             if (!hci_le_supported()){
1756                 // SKIP LE init for Classic only configuration
1757                 hci_init_done();
1758                 return;
1759             }
1760             break;
1761 
1762 #else /* !ENABLE_SCO_OVER_HCI */
1763 
1764         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1765 #ifdef ENABLE_BLE
1766             if (hci_le_supported()){
1767                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1768                 return;
1769             }
1770 #endif
1771             // SKIP LE init for Classic only configuration
1772             hci_init_done();
1773             return;
1774 #endif /* ENABLE_SCO_OVER_HCI */
1775 
1776 // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1
1777 #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL)
1778         // Response to command before init done state -> init done
1779         case (HCI_INIT_DONE-1):
1780             hci_init_done();
1781             return;
1782 #endif
1783 
1784         default:
1785             break;
1786     }
1787     hci_initializing_next_state();
1788 }
1789 
1790 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
1791     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
1792     bd_addr_t bd_address;
1793     memcpy(&bd_address, conn->address, 6);
1794 
1795 #ifdef ENABLE_CLASSIC
1796     // cache needed data
1797     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1798 #endif
1799 
1800     // connection failed, remove entry
1801     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1802     btstack_memory_hci_connection_free( conn );
1803 
1804 #ifdef ENABLE_CLASSIC
1805     // notify client if dedicated bonding
1806     if (notify_dedicated_bonding_failed){
1807         log_info("hci notify_dedicated_bonding_failed");
1808         hci_emit_dedicated_bonding_result(bd_address, status);
1809     }
1810 
1811     // if authentication error, also delete link key
1812     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
1813         gap_drop_link_key_for_bd_addr(bd_address);
1814     }
1815 #endif
1816 }
1817 
1818 static void event_handler(uint8_t *packet, int size){
1819 
1820     uint16_t event_length = packet[1];
1821 
1822     // assert packet is complete
1823     if (size != event_length + 2){
1824         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1825         return;
1826     }
1827 
1828     bd_addr_t addr;
1829     bd_addr_type_t addr_type;
1830     hci_con_handle_t handle;
1831     hci_connection_t * conn;
1832     int i;
1833     int create_connection_cmd;
1834 
1835 #ifdef ENABLE_CLASSIC
1836     uint8_t link_type;
1837 #endif
1838 
1839     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1840 
1841     switch (hci_event_packet_get_type(packet)) {
1842 
1843         case HCI_EVENT_COMMAND_COMPLETE:
1844             // get num cmd packets - limit to 1 to reduce complexity
1845             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1846 
1847             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1848                 if (packet[5]) break;
1849                 // terminate, name 248 chars
1850                 packet[6+248] = 0;
1851                 log_info("local name: %s", &packet[6]);
1852             }
1853             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1854                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1855                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1856                     uint16_t acl_len = little_endian_read_16(packet, 6);
1857                     uint16_t sco_len = packet[8];
1858 
1859                     // determine usable ACL/SCO payload size
1860                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1861                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1862 
1863                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1864                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1865 
1866                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1867                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1868                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1869                 }
1870             }
1871 #ifdef ENABLE_BLE
1872             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1873                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1874                 hci_stack->le_acl_packets_total_num  = packet[8];
1875                 // determine usable ACL payload size
1876                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1877                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1878                 }
1879                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1880             }
1881 #endif
1882 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1883             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1884                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1885                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1886                 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);
1887             }
1888 #endif
1889 #ifdef ENABLE_LE_CENTRAL
1890             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1891                 hci_stack->le_whitelist_capacity = packet[6];
1892                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1893             }
1894 #endif
1895             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1896                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1897 				hci_stack->local_bd_addr);
1898                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1899                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1900 #ifdef ENABLE_CLASSIC
1901                 if (hci_stack->link_key_db){
1902                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1903                 }
1904 #endif
1905             }
1906 #ifdef ENABLE_CLASSIC
1907             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1908                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1909             }
1910             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1911                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1912                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1913                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1914                     hci_emit_event(event, sizeof(event), 1);
1915                 }
1916             }
1917 #endif
1918 
1919             // Note: HCI init checks
1920             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1921                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1922 
1923 #ifdef ENABLE_CLASSIC
1924                 // determine usable ACL packet types based on host buffer size and supported features
1925                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1926                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1927 #endif
1928                 // Classic/LE
1929                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1930             }
1931             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1932                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1933                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1934                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1935                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1936                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1937                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1938             }
1939             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1940                 hci_stack->local_supported_commands[0] =
1941                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1942                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1943                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1944                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3
1945                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0
1946                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2;   // bit 5 = Octet 35, bit 3
1947                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1948             }
1949 #ifdef ENABLE_CLASSIC
1950             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1951                 if (packet[5] == 0){
1952                     hci_stack->synchronous_flow_control_enabled = 1;
1953                 }
1954             }
1955 #endif
1956             break;
1957 
1958         case HCI_EVENT_COMMAND_STATUS:
1959             // get num cmd packets - limit to 1 to reduce complexity
1960             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1961 
1962             // check command status to detected failed outgoing connections
1963             create_connection_cmd = 0;
1964 #ifdef ENABLE_CLASSIC
1965             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
1966                 create_connection_cmd = 1;
1967             }
1968 #endif
1969 #ifdef ENABLE_LE_CENTRAL
1970             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
1971                 create_connection_cmd = 1;
1972             }
1973 #endif
1974             if (create_connection_cmd) {
1975                 uint8_t status = hci_event_command_status_get_status(packet);
1976                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, hci_stack->outgoing_addr_type);
1977                 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);
1978 
1979                 // reset outgoing address info
1980                 memset(hci_stack->outgoing_addr, 0, 6);
1981                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
1982 
1983                 // error => outgoing connection failed
1984                 if ((conn != NULL) && (status != 0)){
1985                     hci_handle_connection_failed(conn, status);
1986                 }
1987             }
1988             break;
1989 
1990         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1991             int offset = 3;
1992             for (i=0; i<packet[2];i++){
1993                 handle = little_endian_read_16(packet, offset) & 0x0fff;
1994                 offset += 2;
1995                 uint16_t num_packets = little_endian_read_16(packet, offset);
1996                 offset += 2;
1997 
1998                 conn = hci_connection_for_handle(handle);
1999                 if (!conn){
2000                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
2001                     continue;
2002                 }
2003 
2004                 if (conn->address_type == BD_ADDR_TYPE_SCO){
2005 #ifdef ENABLE_CLASSIC
2006                     if (conn->num_sco_packets_sent >= num_packets){
2007                         conn->num_sco_packets_sent -= num_packets;
2008                     } else {
2009                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
2010                         conn->num_sco_packets_sent = 0;
2011                     }
2012                     hci_notify_if_sco_can_send_now();
2013 #endif
2014                 } else {
2015                     if (conn->num_acl_packets_sent >= num_packets){
2016                         conn->num_acl_packets_sent -= num_packets;
2017                     } else {
2018                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
2019                         conn->num_acl_packets_sent = 0;
2020                     }
2021                 }
2022                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
2023             }
2024             break;
2025         }
2026 
2027 #ifdef ENABLE_CLASSIC
2028         case HCI_EVENT_INQUIRY_COMPLETE:
2029             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2030                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2031                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2032                 hci_emit_event(event, sizeof(event), 1);
2033             }
2034             break;
2035         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2036             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2037                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2038             }
2039             break;
2040         case HCI_EVENT_CONNECTION_REQUEST:
2041             reverse_bd_addr(&packet[2], addr);
2042             // TODO: eval COD 8-10
2043             link_type = packet[11];
2044             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
2045             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
2046             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2047             if (!conn) {
2048                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2049             }
2050             if (!conn) {
2051                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
2052                 hci_stack->decline_reason = 0x0d;
2053                 bd_addr_copy(hci_stack->decline_addr, addr);
2054                 break;
2055             }
2056             conn->role  = HCI_ROLE_SLAVE;
2057             conn->state = RECEIVED_CONNECTION_REQUEST;
2058             // store info about eSCO
2059             if (link_type == 0x02){
2060                 conn->remote_supported_feature_eSCO = 1;
2061             }
2062             hci_run();
2063             break;
2064 
2065         case HCI_EVENT_CONNECTION_COMPLETE:
2066             // Connection management
2067             reverse_bd_addr(&packet[5], addr);
2068             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2069             addr_type = BD_ADDR_TYPE_CLASSIC;
2070             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2071             if (conn) {
2072                 if (!packet[2]){
2073                     conn->state = OPEN;
2074                     conn->con_handle = little_endian_read_16(packet, 3);
2075                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
2076 
2077                     // restart timer
2078                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2079                     btstack_run_loop_add_timer(&conn->timeout);
2080 
2081                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2082 
2083                     hci_emit_nr_connections_changed();
2084                 } else {
2085                     // connection failed
2086                     hci_handle_connection_failed(conn, packet[2]);
2087                 }
2088             }
2089             break;
2090 
2091         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2092             reverse_bd_addr(&packet[5], addr);
2093             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2094             if (packet[2]){
2095                 // connection failed
2096                 break;
2097             }
2098             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2099             if (!conn) {
2100                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2101             }
2102             if (!conn) {
2103                 break;
2104             }
2105             conn->state = OPEN;
2106             conn->con_handle = little_endian_read_16(packet, 3);
2107 
2108 #ifdef ENABLE_SCO_OVER_HCI
2109             // update SCO
2110             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2111                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2112             }
2113 #endif
2114             break;
2115 
2116         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2117             handle = little_endian_read_16(packet, 3);
2118             conn = hci_connection_for_handle(handle);
2119             if (!conn) break;
2120             if (!packet[2]){
2121                 uint8_t * features = &packet[5];
2122                 if (features[6] & (1 << 3)){
2123                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
2124                 }
2125                 if (features[3] & (1<<7)){
2126                     conn->remote_supported_feature_eSCO = 1;
2127                 }
2128             }
2129             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2130             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
2131             if (conn->bonding_flags & BONDING_DEDICATED){
2132                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2133             }
2134             break;
2135 
2136         case HCI_EVENT_LINK_KEY_REQUEST:
2137             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2138             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2139             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2140             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2141             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2142             hci_run();
2143             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2144             return;
2145 
2146         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2147             reverse_bd_addr(&packet[2], addr);
2148             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2149             if (!conn) break;
2150             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2151             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2152             // Change Connection Encryption keeps link key type
2153             if (link_key_type != CHANGED_COMBINATION_KEY){
2154                 conn->link_key_type = link_key_type;
2155             }
2156             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2157             // still forward event to allow dismiss of pairing dialog
2158             break;
2159         }
2160 
2161         case HCI_EVENT_PIN_CODE_REQUEST:
2162             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2163             // non-bondable mode: pin code negative reply will be sent
2164             if (!hci_stack->bondable){
2165                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2166                 hci_run();
2167                 return;
2168             }
2169             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2170             if (!hci_stack->link_key_db) break;
2171             hci_event_pin_code_request_get_bd_addr(packet, addr);
2172             hci_stack->link_key_db->delete_link_key(addr);
2173             break;
2174 
2175         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2176             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2177             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2178             break;
2179 
2180         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2181             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2182             if (!hci_stack->ssp_auto_accept) break;
2183             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2184             break;
2185 
2186         case HCI_EVENT_USER_PASSKEY_REQUEST:
2187             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2188             if (!hci_stack->ssp_auto_accept) break;
2189             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2190             break;
2191         case HCI_EVENT_MODE_CHANGE:
2192             handle = hci_event_mode_change_get_handle(packet);
2193             conn = hci_connection_for_handle(handle);
2194             if (!conn) break;
2195             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2196             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2197             break;
2198 #endif
2199 
2200         case HCI_EVENT_ENCRYPTION_CHANGE:
2201             handle = little_endian_read_16(packet, 3);
2202             conn = hci_connection_for_handle(handle);
2203             if (!conn) break;
2204             if (packet[2] == 0) {
2205                 if (packet[5]){
2206                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2207                 } else {
2208                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2209                 }
2210             }
2211 #ifdef ENABLE_CLASSIC
2212             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2213 #endif
2214             break;
2215 
2216 #ifdef ENABLE_CLASSIC
2217         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2218             handle = little_endian_read_16(packet, 3);
2219             conn = hci_connection_for_handle(handle);
2220             if (!conn) break;
2221 
2222             // dedicated bonding: send result and disconnect
2223             if (conn->bonding_flags & BONDING_DEDICATED){
2224                 conn->bonding_flags &= ~BONDING_DEDICATED;
2225                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2226                 conn->bonding_status = packet[2];
2227                 break;
2228             }
2229 
2230             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2231                 // link key sufficient for requested security
2232                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2233                 break;
2234             }
2235             // not enough
2236             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2237             break;
2238 #endif
2239 
2240         // HCI_EVENT_DISCONNECTION_COMPLETE
2241         // has been split, to first notify stack before shutting connection down
2242         // see end of function, too.
2243         case HCI_EVENT_DISCONNECTION_COMPLETE:
2244             if (packet[2]) break;   // status != 0
2245             handle = little_endian_read_16(packet, 3);
2246             // drop outgoing ACL fragments if it is for closed connection
2247             if (hci_stack->acl_fragmentation_total_size > 0) {
2248                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2249                     log_info("hci: drop fragmented ACL data for closed connection");
2250                      hci_stack->acl_fragmentation_total_size = 0;
2251                      hci_stack->acl_fragmentation_pos = 0;
2252                 }
2253             }
2254 
2255             // re-enable advertisements for le connections if active
2256             conn = hci_connection_for_handle(handle);
2257             if (!conn) break;
2258             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2259 #ifdef ENABLE_BLE
2260 #ifdef ENABLE_LE_PERIPHERAL
2261             if (hci_is_le_connection(conn)){
2262                 hci_reenable_advertisements_if_needed();
2263             }
2264 #endif
2265 #endif
2266             break;
2267 
2268         case HCI_EVENT_HARDWARE_ERROR:
2269             log_error("Hardware Error: 0x%02x", packet[2]);
2270             if (hci_stack->hardware_error_callback){
2271                 (*hci_stack->hardware_error_callback)(packet[2]);
2272             } else {
2273                 // if no special requests, just reboot stack
2274                 hci_power_control_off();
2275                 hci_power_control_on();
2276             }
2277             break;
2278 
2279 #ifdef ENABLE_CLASSIC
2280         case HCI_EVENT_ROLE_CHANGE:
2281             if (packet[2]) break;   // status != 0
2282             reverse_bd_addr(&packet[3], addr);
2283             addr_type = BD_ADDR_TYPE_CLASSIC;
2284             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2285             if (!conn) break;
2286             conn->role = packet[9];
2287             break;
2288 #endif
2289 
2290         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2291             // release packet buffer only for asynchronous transport and if there are not further fragements
2292             if (hci_transport_synchronous()) {
2293                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2294                 return; // instead of break: to avoid re-entering hci_run()
2295             }
2296             if (hci_stack->acl_fragmentation_total_size) break;
2297             hci_release_packet_buffer();
2298 
2299             // L2CAP receives this event via the hci_emit_event below
2300 
2301 #ifdef ENABLE_CLASSIC
2302             // For SCO, we do the can_send_now_check here
2303             hci_notify_if_sco_can_send_now();
2304 #endif
2305             break;
2306 
2307 #ifdef ENABLE_CLASSIC
2308         case HCI_EVENT_SCO_CAN_SEND_NOW:
2309             // For SCO, we do the can_send_now_check here
2310             hci_notify_if_sco_can_send_now();
2311             return;
2312 
2313         // explode inquriy results for easier consumption
2314         case HCI_EVENT_INQUIRY_RESULT:
2315         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2316         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2317             gap_inquiry_explode(packet);
2318             break;
2319 #endif
2320 
2321 #ifdef ENABLE_BLE
2322         case HCI_EVENT_LE_META:
2323             switch (packet[2]){
2324 #ifdef ENABLE_LE_CENTRAL
2325                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2326                     // log_info("advertising report received");
2327                     if (!hci_stack->le_scanning_enabled) break;
2328                     le_handle_advertisement_report(packet, size);
2329                     break;
2330 #endif
2331                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2332                     // Connection management
2333                     reverse_bd_addr(&packet[8], addr);
2334                     addr_type = (bd_addr_type_t)packet[7];
2335                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2336                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2337 
2338 #ifdef ENABLE_LE_CENTRAL
2339                     // if auto-connect, remove from whitelist in both roles
2340                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2341                         hci_remove_from_whitelist(addr_type, addr);
2342                     }
2343                     // handle error: error is reported only to the initiator -> outgoing connection
2344                     if (packet[3]){
2345 
2346                         // handle cancelled outgoing connection
2347                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2348                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2349                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2350                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2351                             conn = gap_get_outgoing_connection();
2352                         }
2353 
2354                         // outgoing connection establishment is done
2355                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2356                         // remove entry
2357                         if (conn){
2358                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2359                             btstack_memory_hci_connection_free( conn );
2360                         }
2361                         break;
2362                     }
2363 #endif
2364                     // on success, both hosts receive connection complete event
2365                     if (packet[6] == HCI_ROLE_MASTER){
2366 #ifdef ENABLE_LE_CENTRAL
2367                         // if we're master, it was an outgoing connection and we're done with it
2368                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2369 #endif
2370                     } else {
2371 #ifdef ENABLE_LE_PERIPHERAL
2372                         // if we're slave, it was an incoming connection, advertisements have stopped
2373                         hci_stack->le_advertisements_active = 0;
2374 #endif
2375                     }
2376                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2377                     if (!conn){
2378                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2379                     }
2380                     // no memory, sorry.
2381                     if (!conn){
2382                         break;
2383                     }
2384 
2385                     conn->state = OPEN;
2386                     conn->role  = packet[6];
2387                     conn->con_handle = little_endian_read_16(packet, 4);
2388 
2389 #ifdef ENABLE_LE_PERIPHERAL
2390                     if (packet[6] == HCI_ROLE_SLAVE){
2391                         hci_reenable_advertisements_if_needed();
2392                     }
2393 #endif
2394 
2395                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2396 
2397                     // restart timer
2398                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2399                     // btstack_run_loop_add_timer(&conn->timeout);
2400 
2401                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2402 
2403                     hci_emit_nr_connections_changed();
2404                     break;
2405 
2406             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2407 
2408                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
2409                     // connection
2410                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
2411                     conn = hci_connection_for_handle(handle);
2412                     if (conn) {
2413                         // read arguments
2414                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
2415                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
2416                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
2417                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
2418 
2419                         // validate against current connection parameter range
2420                         le_connection_parameter_range_t existing_range;
2421                         gap_get_connection_parameter_range(&existing_range);
2422                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
2423                         if (update_parameter){
2424                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
2425                             conn->le_conn_interval_min = le_conn_interval_min;
2426                             conn->le_conn_interval_max = le_conn_interval_max;
2427                             conn->le_conn_latency = le_conn_latency;
2428                             conn->le_supervision_timeout = le_supervision_timeout;
2429                         } else {
2430                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2431                         }
2432                     }
2433                     break;
2434                 default:
2435                     break;
2436             }
2437             break;
2438 #endif
2439         case HCI_EVENT_VENDOR_SPECIFIC:
2440             // Vendor specific commands often create vendor specific event instead of num completed packets
2441             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
2442             switch (hci_stack->manufacturer){
2443                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
2444                     hci_stack->num_cmd_packets = 1;
2445                     break;
2446                 default:
2447                     break;
2448             }
2449             break;
2450         default:
2451             break;
2452     }
2453 
2454     // handle BT initialization
2455     if (hci_stack->state == HCI_STATE_INITIALIZING){
2456         hci_initializing_event_handler(packet, size);
2457     }
2458 
2459     // help with BT sleep
2460     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2461         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2462         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2463         hci_initializing_next_state();
2464     }
2465 
2466     // notify upper stack
2467 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2468 
2469     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2470     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2471         if (!packet[2]){
2472             handle = little_endian_read_16(packet, 3);
2473             hci_connection_t * aConn = hci_connection_for_handle(handle);
2474             if (aConn) {
2475                 uint8_t status = aConn->bonding_status;
2476                 uint16_t flags = aConn->bonding_flags;
2477                 bd_addr_t bd_address;
2478                 memcpy(&bd_address, aConn->address, 6);
2479                 hci_shutdown_connection(aConn);
2480                 // connection struct is gone, don't access anymore
2481                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2482                     hci_emit_dedicated_bonding_result(bd_address, status);
2483                 }
2484             }
2485         }
2486     }
2487 
2488 	// execute main loop
2489 	hci_run();
2490 }
2491 
2492 #ifdef ENABLE_CLASSIC
2493 static void sco_handler(uint8_t * packet, uint16_t size){
2494     if (!hci_stack->sco_packet_handler) return;
2495     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2496 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2497     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2498     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2499     if (conn){
2500         conn->num_packets_completed++;
2501         hci_stack->host_completed_packets = 1;
2502         hci_run();
2503     }
2504 #endif
2505 }
2506 #endif
2507 
2508 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2509     hci_dump_packet(packet_type, 1, packet, size);
2510     switch (packet_type) {
2511         case HCI_EVENT_PACKET:
2512             event_handler(packet, size);
2513             break;
2514         case HCI_ACL_DATA_PACKET:
2515             acl_handler(packet, size);
2516             break;
2517 #ifdef ENABLE_CLASSIC
2518         case HCI_SCO_DATA_PACKET:
2519             sco_handler(packet, size);
2520             break;
2521 #endif
2522         default:
2523             break;
2524     }
2525 }
2526 
2527 /**
2528  * @brief Add event packet handler.
2529  */
2530 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2531     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2532 }
2533 
2534 
2535 /** Register HCI packet handlers */
2536 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2537     hci_stack->acl_packet_handler = handler;
2538 }
2539 
2540 #ifdef ENABLE_CLASSIC
2541 /**
2542  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2543  */
2544 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2545     hci_stack->sco_packet_handler = handler;
2546 }
2547 #endif
2548 
2549 static void hci_state_reset(void){
2550     // no connections yet
2551     hci_stack->connections = NULL;
2552 
2553     // keep discoverable/connectable as this has been requested by the client(s)
2554     // hci_stack->discoverable = 0;
2555     // hci_stack->connectable = 0;
2556     // hci_stack->bondable = 1;
2557     // hci_stack->own_addr_type = 0;
2558 
2559     // buffer is free
2560     hci_stack->hci_packet_buffer_reserved = 0;
2561 
2562     // no pending cmds
2563     hci_stack->decline_reason = 0;
2564     hci_stack->new_scan_enable_value = 0xff;
2565 
2566     // LE
2567 #ifdef ENABLE_BLE
2568     memset(hci_stack->le_random_address, 0, 6);
2569     hci_stack->le_random_address_set = 0;
2570 #endif
2571 #ifdef ENABLE_LE_CENTRAL
2572     hci_stack->le_scanning_active  = 0;
2573     hci_stack->le_scan_type = 0xff;
2574     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2575     hci_stack->le_whitelist = 0;
2576     hci_stack->le_whitelist_capacity = 0;
2577 #endif
2578 }
2579 
2580 #ifdef ENABLE_CLASSIC
2581 /**
2582  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2583  */
2584 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2585     // store and open remote device db
2586     hci_stack->link_key_db = link_key_db;
2587     if (hci_stack->link_key_db) {
2588         hci_stack->link_key_db->open();
2589     }
2590 }
2591 #endif
2592 
2593 void hci_init(const hci_transport_t *transport, const void *config){
2594 
2595 #ifdef HAVE_MALLOC
2596     if (!hci_stack) {
2597         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2598     }
2599 #else
2600     hci_stack = &hci_stack_static;
2601 #endif
2602     memset(hci_stack, 0, sizeof(hci_stack_t));
2603 
2604     // reference to use transport layer implementation
2605     hci_stack->hci_transport = transport;
2606 
2607     // reference to used config
2608     hci_stack->config = config;
2609 
2610     // setup pointer for outgoing packet buffer
2611     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2612 
2613     // max acl payload size defined in config.h
2614     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2615 
2616     // register packet handlers with transport
2617     transport->register_packet_handler(&packet_handler);
2618 
2619     hci_stack->state = HCI_STATE_OFF;
2620 
2621     // class of device
2622     hci_stack->class_of_device = 0x007a020c; // Smartphone
2623 
2624     // bondable by default
2625     hci_stack->bondable = 1;
2626 
2627 #ifdef ENABLE_CLASSIC
2628     // classic name
2629     hci_stack->local_name = default_classic_name;
2630 
2631     // Master slave policy
2632     hci_stack->master_slave_policy = 1;
2633 #endif
2634 
2635     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2636     hci_stack->ssp_enable = 1;
2637     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2638     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2639     hci_stack->ssp_auto_accept = 1;
2640 
2641     // voice setting - signed 16 bit pcm data with CVSD over the air
2642     hci_stack->sco_voice_setting = 0x60;
2643 
2644 #ifdef ENABLE_LE_CENTRAL
2645     // connection parameter to use for outgoing connections
2646     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2647     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2648     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2649     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2650     hci_stack->le_connection_latency      = 4;         // 4
2651     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2652     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2653     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2654 #endif
2655 
2656 #ifdef ENABLE_LE_PERIPHERAL
2657     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
2658 #endif
2659 
2660     // connection parameter range used to answer connection parameter update requests in l2cap
2661     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2662     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2663     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2664     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2665     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2666     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2667 
2668     hci_state_reset();
2669 }
2670 
2671 /**
2672  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2673  */
2674 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2675     hci_stack->chipset = chipset_driver;
2676 
2677     // reset chipset driver - init is also called on power_up
2678     if (hci_stack->chipset && hci_stack->chipset->init){
2679         hci_stack->chipset->init(hci_stack->config);
2680     }
2681 }
2682 
2683 /**
2684  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2685  */
2686 void hci_set_control(const btstack_control_t *hardware_control){
2687     // references to used control implementation
2688     hci_stack->control = hardware_control;
2689     // init with transport config
2690     hardware_control->init(hci_stack->config);
2691 }
2692 
2693 void hci_close(void){
2694     // close remote device db
2695     if (hci_stack->link_key_db) {
2696         hci_stack->link_key_db->close();
2697     }
2698 
2699     btstack_linked_list_iterator_t lit;
2700     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2701     while (btstack_linked_list_iterator_has_next(&lit)){
2702         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2703         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2704         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2705         hci_shutdown_connection(connection);
2706     }
2707 
2708     hci_power_control(HCI_POWER_OFF);
2709 
2710 #ifdef HAVE_MALLOC
2711     free(hci_stack);
2712 #endif
2713     hci_stack = NULL;
2714 }
2715 
2716 #ifdef ENABLE_CLASSIC
2717 void gap_set_class_of_device(uint32_t class_of_device){
2718     hci_stack->class_of_device = class_of_device;
2719 }
2720 
2721 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
2722     hci_stack->default_link_policy_settings = default_link_policy_settings;
2723 }
2724 
2725 void hci_disable_l2cap_timeout_check(void){
2726     disable_l2cap_timeouts = 1;
2727 }
2728 #endif
2729 
2730 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2731 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2732 void hci_set_bd_addr(bd_addr_t addr){
2733     memcpy(hci_stack->custom_bd_addr, addr, 6);
2734     hci_stack->custom_bd_addr_set = 1;
2735 }
2736 #endif
2737 
2738 // State-Module-Driver overview
2739 // state                    module  low-level
2740 // HCI_STATE_OFF             off      close
2741 // HCI_STATE_INITIALIZING,   on       open
2742 // HCI_STATE_WORKING,        on       open
2743 // HCI_STATE_HALTING,        on       open
2744 // HCI_STATE_SLEEPING,    off/sleep   close
2745 // HCI_STATE_FALLING_ASLEEP  on       open
2746 
2747 static int hci_power_control_on(void){
2748 
2749     // power on
2750     int err = 0;
2751     if (hci_stack->control && hci_stack->control->on){
2752         err = (*hci_stack->control->on)();
2753     }
2754     if (err){
2755         log_error( "POWER_ON failed");
2756         hci_emit_hci_open_failed();
2757         return err;
2758     }
2759 
2760     // int chipset driver
2761     if (hci_stack->chipset && hci_stack->chipset->init){
2762         hci_stack->chipset->init(hci_stack->config);
2763     }
2764 
2765     // init transport
2766     if (hci_stack->hci_transport->init){
2767         hci_stack->hci_transport->init(hci_stack->config);
2768     }
2769 
2770     // open transport
2771     err = hci_stack->hci_transport->open();
2772     if (err){
2773         log_error( "HCI_INIT failed, turning Bluetooth off again");
2774         if (hci_stack->control && hci_stack->control->off){
2775             (*hci_stack->control->off)();
2776         }
2777         hci_emit_hci_open_failed();
2778         return err;
2779     }
2780     return 0;
2781 }
2782 
2783 static void hci_power_control_off(void){
2784 
2785     log_info("hci_power_control_off");
2786 
2787     // close low-level device
2788     hci_stack->hci_transport->close();
2789 
2790     log_info("hci_power_control_off - hci_transport closed");
2791 
2792     // power off
2793     if (hci_stack->control && hci_stack->control->off){
2794         (*hci_stack->control->off)();
2795     }
2796 
2797     log_info("hci_power_control_off - control closed");
2798 
2799     hci_stack->state = HCI_STATE_OFF;
2800 }
2801 
2802 static void hci_power_control_sleep(void){
2803 
2804     log_info("hci_power_control_sleep");
2805 
2806 #if 0
2807     // don't close serial port during sleep
2808 
2809     // close low-level device
2810     hci_stack->hci_transport->close(hci_stack->config);
2811 #endif
2812 
2813     // sleep mode
2814     if (hci_stack->control && hci_stack->control->sleep){
2815         (*hci_stack->control->sleep)();
2816     }
2817 
2818     hci_stack->state = HCI_STATE_SLEEPING;
2819 }
2820 
2821 static int hci_power_control_wake(void){
2822 
2823     log_info("hci_power_control_wake");
2824 
2825     // wake on
2826     if (hci_stack->control && hci_stack->control->wake){
2827         (*hci_stack->control->wake)();
2828     }
2829 
2830 #if 0
2831     // open low-level device
2832     int err = hci_stack->hci_transport->open(hci_stack->config);
2833     if (err){
2834         log_error( "HCI_INIT failed, turning Bluetooth off again");
2835         if (hci_stack->control && hci_stack->control->off){
2836             (*hci_stack->control->off)();
2837         }
2838         hci_emit_hci_open_failed();
2839         return err;
2840     }
2841 #endif
2842 
2843     return 0;
2844 }
2845 
2846 static void hci_power_transition_to_initializing(void){
2847     // set up state machine
2848     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2849     hci_stack->hci_packet_buffer_reserved = 0;
2850     hci_stack->state = HCI_STATE_INITIALIZING;
2851     hci_stack->substate = HCI_INIT_SEND_RESET;
2852 }
2853 
2854 int hci_power_control(HCI_POWER_MODE power_mode){
2855 
2856     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2857 
2858     int err = 0;
2859     switch (hci_stack->state){
2860 
2861         case HCI_STATE_OFF:
2862             switch (power_mode){
2863                 case HCI_POWER_ON:
2864                     err = hci_power_control_on();
2865                     if (err) {
2866                         log_error("hci_power_control_on() error %d", err);
2867                         return err;
2868                     }
2869                     hci_power_transition_to_initializing();
2870                     break;
2871                 case HCI_POWER_OFF:
2872                     // do nothing
2873                     break;
2874                 case HCI_POWER_SLEEP:
2875                     // do nothing (with SLEEP == OFF)
2876                     break;
2877             }
2878             break;
2879 
2880         case HCI_STATE_INITIALIZING:
2881             switch (power_mode){
2882                 case HCI_POWER_ON:
2883                     // do nothing
2884                     break;
2885                 case HCI_POWER_OFF:
2886                     // no connections yet, just turn it off
2887                     hci_power_control_off();
2888                     break;
2889                 case HCI_POWER_SLEEP:
2890                     // no connections yet, just turn it off
2891                     hci_power_control_sleep();
2892                     break;
2893             }
2894             break;
2895 
2896         case HCI_STATE_WORKING:
2897             switch (power_mode){
2898                 case HCI_POWER_ON:
2899                     // do nothing
2900                     break;
2901                 case HCI_POWER_OFF:
2902                     // see hci_run
2903                     hci_stack->state = HCI_STATE_HALTING;
2904                     break;
2905                 case HCI_POWER_SLEEP:
2906                     // see hci_run
2907                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2908                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2909                     break;
2910             }
2911             break;
2912 
2913         case HCI_STATE_HALTING:
2914             switch (power_mode){
2915                 case HCI_POWER_ON:
2916                     hci_power_transition_to_initializing();
2917                     break;
2918                 case HCI_POWER_OFF:
2919                     // do nothing
2920                     break;
2921                 case HCI_POWER_SLEEP:
2922                     // see hci_run
2923                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2924                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2925                     break;
2926             }
2927             break;
2928 
2929         case HCI_STATE_FALLING_ASLEEP:
2930             switch (power_mode){
2931                 case HCI_POWER_ON:
2932 
2933 #ifdef HAVE_PLATFORM_IPHONE_OS
2934                     // nothing to do, if H4 supports power management
2935                     if (btstack_control_iphone_power_management_enabled()){
2936                         hci_stack->state = HCI_STATE_INITIALIZING;
2937                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2938                         break;
2939                     }
2940 #endif
2941                     hci_power_transition_to_initializing();
2942                     break;
2943                 case HCI_POWER_OFF:
2944                     // see hci_run
2945                     hci_stack->state = HCI_STATE_HALTING;
2946                     break;
2947                 case HCI_POWER_SLEEP:
2948                     // do nothing
2949                     break;
2950             }
2951             break;
2952 
2953         case HCI_STATE_SLEEPING:
2954             switch (power_mode){
2955                 case HCI_POWER_ON:
2956 
2957 #ifdef HAVE_PLATFORM_IPHONE_OS
2958                     // nothing to do, if H4 supports power management
2959                     if (btstack_control_iphone_power_management_enabled()){
2960                         hci_stack->state = HCI_STATE_INITIALIZING;
2961                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2962                         hci_update_scan_enable();
2963                         break;
2964                     }
2965 #endif
2966                     err = hci_power_control_wake();
2967                     if (err) return err;
2968                     hci_power_transition_to_initializing();
2969                     break;
2970                 case HCI_POWER_OFF:
2971                     hci_stack->state = HCI_STATE_HALTING;
2972                     break;
2973                 case HCI_POWER_SLEEP:
2974                     // do nothing
2975                     break;
2976             }
2977             break;
2978     }
2979 
2980     // create internal event
2981 	hci_emit_state();
2982 
2983 	// trigger next/first action
2984 	hci_run();
2985 
2986     return 0;
2987 }
2988 
2989 
2990 #ifdef ENABLE_CLASSIC
2991 
2992 static void hci_update_scan_enable(void){
2993     // 2 = page scan, 1 = inq scan
2994     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2995     hci_run();
2996 }
2997 
2998 void gap_discoverable_control(uint8_t enable){
2999     if (enable) enable = 1; // normalize argument
3000 
3001     if (hci_stack->discoverable == enable){
3002         hci_emit_discoverable_enabled(hci_stack->discoverable);
3003         return;
3004     }
3005 
3006     hci_stack->discoverable = enable;
3007     hci_update_scan_enable();
3008 }
3009 
3010 void gap_connectable_control(uint8_t enable){
3011     if (enable) enable = 1; // normalize argument
3012 
3013     // don't emit event
3014     if (hci_stack->connectable == enable) return;
3015 
3016     hci_stack->connectable = enable;
3017     hci_update_scan_enable();
3018 }
3019 #endif
3020 
3021 void gap_local_bd_addr(bd_addr_t address_buffer){
3022     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3023 }
3024 
3025 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3026 static void hci_host_num_completed_packets(void){
3027 
3028     // create packet manually as arrays are not supported and num_commands should not get reduced
3029     hci_reserve_packet_buffer();
3030     uint8_t * packet = hci_get_outgoing_packet_buffer();
3031 
3032     uint16_t size = 0;
3033     uint16_t num_handles = 0;
3034     packet[size++] = 0x35;
3035     packet[size++] = 0x0c;
3036     size++;  // skip param len
3037     size++;  // skip num handles
3038 
3039     // add { handle, packets } entries
3040     btstack_linked_item_t * it;
3041     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3042         hci_connection_t * connection = (hci_connection_t *) it;
3043         if (connection->num_packets_completed){
3044             little_endian_store_16(packet, size, connection->con_handle);
3045             size += 2;
3046             little_endian_store_16(packet, size, connection->num_packets_completed);
3047             size += 2;
3048             //
3049             num_handles++;
3050             connection->num_packets_completed = 0;
3051         }
3052     }
3053 
3054     packet[2] = size - 3;
3055     packet[3] = num_handles;
3056 
3057     hci_stack->host_completed_packets = 0;
3058 
3059     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3060     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3061 
3062     // release packet buffer for synchronous transport implementations
3063     if (hci_transport_synchronous()){
3064         hci_release_packet_buffer();
3065         hci_emit_transport_packet_sent();
3066     }
3067 }
3068 #endif
3069 
3070 static void hci_run(void){
3071 
3072     // log_info("hci_run: entered");
3073     btstack_linked_item_t * it;
3074 
3075     // send continuation fragments first, as they block the prepared packet buffer
3076     if (hci_stack->acl_fragmentation_total_size > 0) {
3077         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3078         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3079         if (connection) {
3080             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3081                 hci_send_acl_packet_fragments(connection);
3082                 return;
3083             }
3084         } else {
3085             // connection gone -> discard further fragments
3086             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3087             hci_stack->acl_fragmentation_total_size = 0;
3088             hci_stack->acl_fragmentation_pos = 0;
3089         }
3090     }
3091 
3092 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3093     // send host num completed packets next as they don't require num_cmd_packets > 0
3094     if (!hci_can_send_comand_packet_transport()) return;
3095     if (hci_stack->host_completed_packets){
3096         hci_host_num_completed_packets();
3097         return;
3098     }
3099 #endif
3100 
3101     if (!hci_can_send_command_packet_now()) return;
3102 
3103     // global/non-connection oriented commands
3104 
3105 #ifdef ENABLE_CLASSIC
3106     // decline incoming connections
3107     if (hci_stack->decline_reason){
3108         uint8_t reason = hci_stack->decline_reason;
3109         hci_stack->decline_reason = 0;
3110         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3111         return;
3112     }
3113     // send scan enable
3114     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
3115         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3116         hci_stack->new_scan_enable_value = 0xff;
3117         return;
3118     }
3119     // start/stop inquiry
3120     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
3121         uint8_t duration = hci_stack->inquiry_state;
3122         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3123         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3124         return;
3125     }
3126     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3127         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3128         hci_send_cmd(&hci_inquiry_cancel);
3129         return;
3130     }
3131     // remote name request
3132     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3133         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3134         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3135             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3136         return;
3137     }
3138     // pairing
3139     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3140         uint8_t state = hci_stack->gap_pairing_state;
3141         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3142         switch (state){
3143             case GAP_PAIRING_STATE_SEND_PIN:
3144                 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);
3145                 break;
3146             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3147                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3148                 break;
3149             case GAP_PAIRING_STATE_SEND_PASSKEY:
3150                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3151                 break;
3152             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3153                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3154                 break;
3155             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3156                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3157                 break;
3158             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3159                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3160                 break;
3161             default:
3162                 break;
3163         }
3164         return;
3165     }
3166 #endif
3167 
3168 #ifdef ENABLE_BLE
3169     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3170     if ((hci_stack->state == HCI_STATE_WORKING)
3171     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3172 
3173 #ifdef ENABLE_LE_CENTRAL
3174         // handle le scan
3175         if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
3176             hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
3177             hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3178             return;
3179         }
3180         if (hci_stack->le_scan_type != 0xff){
3181             // defaults: active scanning, accept all advertisement packets
3182             int scan_type = hci_stack->le_scan_type;
3183             hci_stack->le_scan_type = 0xff;
3184             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);
3185             return;
3186         }
3187 #endif
3188 #ifdef ENABLE_LE_PERIPHERAL
3189         // le advertisement control
3190         if (hci_stack->le_advertisements_todo){
3191             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3192         }
3193         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3194             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3195             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3196             return;
3197         }
3198         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3199             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3200             hci_send_cmd(&hci_le_set_advertising_parameters,
3201                  hci_stack->le_advertisements_interval_min,
3202                  hci_stack->le_advertisements_interval_max,
3203                  hci_stack->le_advertisements_type,
3204                  hci_stack->le_own_addr_type,
3205                  hci_stack->le_advertisements_direct_address_type,
3206                  hci_stack->le_advertisements_direct_address,
3207                  hci_stack->le_advertisements_channel_map,
3208                  hci_stack->le_advertisements_filter_policy);
3209             return;
3210         }
3211         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3212             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3213             uint8_t adv_data_clean[31];
3214             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3215             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3216             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3217             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3218             return;
3219         }
3220         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3221             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3222             uint8_t scan_data_clean[31];
3223             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3224             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3225             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3226             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3227             return;
3228         }
3229         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3230             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3231             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3232             return;
3233         }
3234 #endif
3235 
3236 #ifdef ENABLE_LE_CENTRAL
3237         //
3238         // LE Whitelist Management
3239         //
3240 
3241         // check if whitelist needs modification
3242         btstack_linked_list_iterator_t lit;
3243         int modification_pending = 0;
3244         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3245         while (btstack_linked_list_iterator_has_next(&lit)){
3246             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3247             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3248                 modification_pending = 1;
3249                 break;
3250             }
3251         }
3252 
3253         if (modification_pending){
3254             // stop connnecting if modification pending
3255             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3256                 hci_send_cmd(&hci_le_create_connection_cancel);
3257                 return;
3258             }
3259 
3260             // add/remove entries
3261             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3262             while (btstack_linked_list_iterator_has_next(&lit)){
3263                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3264                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3265                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3266                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3267                     return;
3268 
3269                 }
3270                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3271                     bd_addr_t address;
3272                     bd_addr_type_t address_type = entry->address_type;
3273                     memcpy(address, entry->address, 6);
3274                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3275                     btstack_memory_whitelist_entry_free(entry);
3276                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3277                     return;
3278                 }
3279             }
3280         }
3281 
3282         // start connecting
3283         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3284             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3285             bd_addr_t null_addr;
3286             memset(null_addr, 0, 6);
3287             hci_send_cmd(&hci_le_create_connection,
3288                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3289                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3290                  1,         // use whitelist
3291                  0,         // peer address type
3292                  null_addr, // peer bd addr
3293                  hci_stack->le_own_addr_type, // our addr type:
3294                  hci_stack->le_connection_interval_min,    // conn interval min
3295                  hci_stack->le_connection_interval_max,    // conn interval max
3296                  hci_stack->le_connection_latency,         // conn latency
3297                  hci_stack->le_supervision_timeout,        // conn latency
3298                  hci_stack->le_minimum_ce_length,          // min ce length
3299                  hci_stack->le_maximum_ce_length           // max ce length
3300                 );
3301             return;
3302         }
3303 #endif
3304     }
3305 #endif
3306 
3307     // send pending HCI commands
3308     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3309         hci_connection_t * connection = (hci_connection_t *) it;
3310 
3311         switch(connection->state){
3312             case SEND_CREATE_CONNECTION:
3313                 switch(connection->address_type){
3314 #ifdef ENABLE_CLASSIC
3315                     case BD_ADDR_TYPE_CLASSIC:
3316                         log_info("sending hci_create_connection");
3317                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3318                         break;
3319 #endif
3320                     default:
3321 #ifdef ENABLE_BLE
3322 #ifdef ENABLE_LE_CENTRAL
3323                         // track outgoing connection
3324                         hci_stack->outgoing_addr_type = connection->address_type;
3325                         memcpy(hci_stack->outgoing_addr, connection->address, 6);
3326                         log_info("sending hci_le_create_connection");
3327                         hci_send_cmd(&hci_le_create_connection,
3328                              hci_stack->le_connection_scan_interval,    // conn scan interval
3329                              hci_stack->le_connection_scan_window,      // conn scan windows
3330                              0,         // don't use whitelist
3331                              connection->address_type, // peer address type
3332                              connection->address,      // peer bd addr
3333                              hci_stack->le_own_addr_type, // our addr type:
3334                              hci_stack->le_connection_interval_min,    // conn interval min
3335                              hci_stack->le_connection_interval_max,    // conn interval max
3336                              hci_stack->le_connection_latency,         // conn latency
3337                              hci_stack->le_supervision_timeout,        // conn latency
3338                              hci_stack->le_minimum_ce_length,          // min ce length
3339                              hci_stack->le_maximum_ce_length          // max ce length
3340                              );
3341                         connection->state = SENT_CREATE_CONNECTION;
3342 #endif
3343 #endif
3344                         break;
3345                 }
3346                 return;
3347 
3348 #ifdef ENABLE_CLASSIC
3349             case RECEIVED_CONNECTION_REQUEST:
3350                 connection->role  = HCI_ROLE_SLAVE;
3351                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3352                     log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3353                     connection->state = ACCEPTED_CONNECTION_REQUEST;
3354                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3355                 }
3356                 return;
3357 #endif
3358 
3359 #ifdef ENABLE_BLE
3360 #ifdef ENABLE_LE_CENTRAL
3361             case SEND_CANCEL_CONNECTION:
3362                 connection->state = SENT_CANCEL_CONNECTION;
3363                 hci_send_cmd(&hci_le_create_connection_cancel);
3364                 return;
3365 #endif
3366 #endif
3367             case SEND_DISCONNECT:
3368                 connection->state = SENT_DISCONNECT;
3369                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3370                 return;
3371 
3372             default:
3373                 break;
3374         }
3375 
3376         // no further commands if connection is about to get shut down
3377         if (connection->state == SENT_DISCONNECT) continue;
3378 
3379 #ifdef ENABLE_CLASSIC
3380         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3381             log_info("responding to link key request");
3382             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3383             link_key_t link_key;
3384             link_key_type_t link_key_type;
3385             if ( hci_stack->link_key_db
3386               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3387               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3388                connection->link_key_type = link_key_type;
3389                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3390             } else {
3391                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3392             }
3393             return;
3394         }
3395 
3396         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3397             log_info("denying to pin request");
3398             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3399             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3400             return;
3401         }
3402 
3403         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3404             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3405             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3406             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3407                 // tweak authentication requirements
3408                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3409                 if (connection->bonding_flags & BONDING_DEDICATED){
3410                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3411                 }
3412                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3413                     authreq |= 1;
3414                 }
3415                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3416             } else {
3417                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3418             }
3419             return;
3420         }
3421 
3422         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3423             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3424             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3425             return;
3426         }
3427 
3428         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3429             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3430             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3431             return;
3432         }
3433 
3434         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3435             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3436             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3437             return;
3438         }
3439 
3440         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3441             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3442             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3443             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3444             return;
3445         }
3446 
3447         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3448             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3449             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3450             return;
3451         }
3452 
3453         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3454             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3455             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3456             return;
3457         }
3458 #endif
3459 
3460         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3461             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3462             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3463             return;
3464         }
3465 
3466 #ifdef ENABLE_CLASSIC
3467         uint16_t sniff_min_interval;
3468         switch (connection->sniff_min_interval){
3469             case 0:
3470                 break;
3471             case 0xffff:
3472                 connection->sniff_min_interval = 0;
3473                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
3474                 return;
3475             default:
3476                 sniff_min_interval = connection->sniff_min_interval;
3477                 connection->sniff_min_interval = 0;
3478                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
3479                 break;
3480         }
3481 #endif
3482 
3483 #ifdef ENABLE_BLE
3484         switch (connection->le_con_parameter_update_state){
3485             // response to L2CAP CON PARAMETER UPDATE REQUEST
3486             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
3487                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3488                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
3489                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3490                     0x0000, 0xffff);
3491                 break;
3492             case CON_PARAMETER_UPDATE_REPLY:
3493                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3494                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
3495                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3496                     0x0000, 0xffff);
3497                 break;
3498             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
3499                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3500                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
3501                 break;
3502             default:
3503                 break;
3504         }
3505 #endif
3506     }
3507 
3508     hci_connection_t * connection;
3509     switch (hci_stack->state){
3510         case HCI_STATE_INITIALIZING:
3511             hci_initializing_run();
3512             break;
3513 
3514         case HCI_STATE_HALTING:
3515 
3516             log_info("HCI_STATE_HALTING");
3517 
3518             // free whitelist entries
3519 #ifdef ENABLE_BLE
3520 #ifdef ENABLE_LE_CENTRAL
3521             {
3522                 btstack_linked_list_iterator_t lit;
3523                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3524                 while (btstack_linked_list_iterator_has_next(&lit)){
3525                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3526                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3527                     btstack_memory_whitelist_entry_free(entry);
3528                 }
3529             }
3530 #endif
3531 #endif
3532             // close all open connections
3533             connection =  (hci_connection_t *) hci_stack->connections;
3534             if (connection){
3535                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3536                 if (!hci_can_send_command_packet_now()) return;
3537 
3538                 // check state
3539                 if (connection->state == SENT_DISCONNECT) return;
3540                 connection->state = SENT_DISCONNECT;
3541 
3542                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3543 
3544                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3545                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3546 
3547                 // ... which would be ignored anyway as we shutdown (free) the connection now
3548                 hci_shutdown_connection(connection);
3549 
3550                 // finally, send the disconnect command
3551                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3552                 return;
3553             }
3554             log_info("HCI_STATE_HALTING, calling off");
3555 
3556             // switch mode
3557             hci_power_control_off();
3558 
3559             log_info("HCI_STATE_HALTING, emitting state");
3560             hci_emit_state();
3561             log_info("HCI_STATE_HALTING, done");
3562             break;
3563 
3564         case HCI_STATE_FALLING_ASLEEP:
3565             switch(hci_stack->substate) {
3566                 case HCI_FALLING_ASLEEP_DISCONNECT:
3567                     log_info("HCI_STATE_FALLING_ASLEEP");
3568                     // close all open connections
3569                     connection =  (hci_connection_t *) hci_stack->connections;
3570 
3571 #ifdef HAVE_PLATFORM_IPHONE_OS
3572                     // don't close connections, if H4 supports power management
3573                     if (btstack_control_iphone_power_management_enabled()){
3574                         connection = NULL;
3575                     }
3576 #endif
3577                     if (connection){
3578 
3579                         // send disconnect
3580                         if (!hci_can_send_command_packet_now()) return;
3581 
3582                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3583                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3584 
3585                         // send disconnected event right away - causes higher layer connections to get closed, too.
3586                         hci_shutdown_connection(connection);
3587                         return;
3588                     }
3589 
3590                     if (hci_classic_supported()){
3591                         // disable page and inquiry scan
3592                         if (!hci_can_send_command_packet_now()) return;
3593 
3594                         log_info("HCI_STATE_HALTING, disabling inq scans");
3595                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3596 
3597                         // continue in next sub state
3598                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3599                         break;
3600                     }
3601                     // no break - fall through for ble-only chips
3602 
3603                 case HCI_FALLING_ASLEEP_COMPLETE:
3604                     log_info("HCI_STATE_HALTING, calling sleep");
3605 #ifdef HAVE_PLATFORM_IPHONE_OS
3606                     // don't actually go to sleep, if H4 supports power management
3607                     if (btstack_control_iphone_power_management_enabled()){
3608                         // SLEEP MODE reached
3609                         hci_stack->state = HCI_STATE_SLEEPING;
3610                         hci_emit_state();
3611                         break;
3612                     }
3613 #endif
3614                     // switch mode
3615                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3616                     hci_emit_state();
3617                     break;
3618 
3619                 default:
3620                     break;
3621             }
3622             break;
3623 
3624         default:
3625             break;
3626     }
3627 }
3628 
3629 int hci_send_cmd_packet(uint8_t *packet, int size){
3630     // house-keeping
3631 
3632     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3633         hci_stack->loopback_mode = packet[3];
3634     }
3635 
3636 #ifdef ENABLE_CLASSIC
3637     bd_addr_t addr;
3638     hci_connection_t * conn;
3639 
3640     // create_connection?
3641     if (IS_COMMAND(packet, hci_create_connection)){
3642         reverse_bd_addr(&packet[3], addr);
3643         log_info("Create_connection to %s", bd_addr_to_str(addr));
3644 
3645         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3646         if (!conn){
3647             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3648             if (!conn){
3649                 // notify client that alloc failed
3650                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3651                 return -1; // packet not sent to controller
3652             }
3653             conn->state = SEND_CREATE_CONNECTION;
3654         }
3655         log_info("conn state %u", conn->state);
3656         switch (conn->state){
3657             // if connection active exists
3658             case OPEN:
3659                 // and OPEN, emit connection complete command
3660                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3661                 return -1; // packet not sent to controller
3662             case SEND_CREATE_CONNECTION:
3663                 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
3664                 break;
3665             default:
3666                 // otherwise, just ignore as it is already in the open process
3667                 return -1; // packet not sent to controller
3668         }
3669         conn->state = SENT_CREATE_CONNECTION;
3670 
3671         // track outgoing connection
3672         hci_stack->outgoing_addr_type = BD_ADDR_TYPE_CLASSIC;
3673         memcpy(hci_stack->outgoing_addr, addr, 6);
3674     }
3675 
3676     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3677         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3678     }
3679     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3680         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3681     }
3682 
3683     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3684         if (hci_stack->link_key_db){
3685             reverse_bd_addr(&packet[3], addr);
3686             hci_stack->link_key_db->delete_link_key(addr);
3687         }
3688     }
3689 
3690     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3691     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3692         reverse_bd_addr(&packet[3], addr);
3693         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3694         if (conn){
3695             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3696         }
3697     }
3698 
3699     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3700     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3701     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3702     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3703         reverse_bd_addr(&packet[3], addr);
3704         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3705         if (conn){
3706             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3707         }
3708     }
3709 
3710 #ifdef ENABLE_SCO_OVER_HCI
3711     // setup_synchronous_connection? Voice setting at offset 22
3712     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3713         // TODO: compare to current setting if sco connection already active
3714         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3715     }
3716     // accept_synchronus_connection? Voice setting at offset 18
3717     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3718         // TODO: compare to current setting if sco connection already active
3719         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3720     }
3721 #endif
3722 #endif
3723 
3724 #ifdef ENABLE_BLE
3725 #ifdef ENABLE_LE_PERIPHERAL
3726     if (IS_COMMAND(packet, hci_le_set_random_address)){
3727         hci_stack->le_random_address_set = 1;
3728         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3729     }
3730     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3731         hci_stack->le_advertisements_active = packet[3];
3732     }
3733 #endif
3734 #ifdef ENABLE_LE_CENTRAL
3735     if (IS_COMMAND(packet, hci_le_create_connection)){
3736         // white list used?
3737         uint8_t initiator_filter_policy = packet[7];
3738         switch (initiator_filter_policy){
3739             case 0:
3740                 // whitelist not used
3741                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3742                 break;
3743             case 1:
3744                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3745                 break;
3746             default:
3747                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3748                 break;
3749         }
3750     }
3751     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3752         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3753     }
3754 #endif
3755 #endif
3756 
3757     hci_stack->num_cmd_packets--;
3758 
3759     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3760     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3761 }
3762 
3763 // disconnect because of security block
3764 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3765     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3766     if (!connection) return;
3767     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3768 }
3769 
3770 
3771 // Configure Secure Simple Pairing
3772 
3773 #ifdef ENABLE_CLASSIC
3774 
3775 // enable will enable SSP during init
3776 void gap_ssp_set_enable(int enable){
3777     hci_stack->ssp_enable = enable;
3778 }
3779 
3780 static int hci_local_ssp_activated(void){
3781     return gap_ssp_supported() && hci_stack->ssp_enable;
3782 }
3783 
3784 // if set, BTstack will respond to io capability request using authentication requirement
3785 void gap_ssp_set_io_capability(int io_capability){
3786     hci_stack->ssp_io_capability = io_capability;
3787 }
3788 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3789     hci_stack->ssp_authentication_requirement = authentication_requirement;
3790 }
3791 
3792 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3793 void gap_ssp_set_auto_accept(int auto_accept){
3794     hci_stack->ssp_auto_accept = auto_accept;
3795 }
3796 #endif
3797 
3798 // va_list part of hci_send_cmd
3799 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3800     if (!hci_can_send_command_packet_now()){
3801         log_error("hci_send_cmd called but cannot send packet now");
3802         return 0;
3803     }
3804 
3805     // for HCI INITIALIZATION
3806     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3807     hci_stack->last_cmd_opcode = cmd->opcode;
3808 
3809     hci_reserve_packet_buffer();
3810     uint8_t * packet = hci_stack->hci_packet_buffer;
3811     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3812     int err = hci_send_cmd_packet(packet, size);
3813 
3814     // release packet buffer for synchronous transport implementations
3815     if (hci_transport_synchronous()){
3816         hci_release_packet_buffer();
3817         hci_emit_transport_packet_sent();
3818     }
3819 
3820     return err;
3821 }
3822 
3823 /**
3824  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3825  */
3826 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3827     va_list argptr;
3828     va_start(argptr, cmd);
3829     int res = hci_send_cmd_va_arg(cmd, argptr);
3830     va_end(argptr);
3831     return res;
3832 }
3833 
3834 // Create various non-HCI events.
3835 // TODO: generalize, use table similar to hci_create_command
3836 
3837 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3838     // dump packet
3839     if (dump) {
3840         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3841     }
3842 
3843     // dispatch to all event handlers
3844     btstack_linked_list_iterator_t it;
3845     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3846     while (btstack_linked_list_iterator_has_next(&it)){
3847         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3848         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3849     }
3850 }
3851 
3852 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3853     if (!hci_stack->acl_packet_handler) return;
3854     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3855 }
3856 
3857 #ifdef ENABLE_CLASSIC
3858 static void hci_notify_if_sco_can_send_now(void){
3859     // notify SCO sender if waiting
3860     if (!hci_stack->sco_waiting_for_can_send_now) return;
3861     if (hci_can_send_sco_packet_now()){
3862         hci_stack->sco_waiting_for_can_send_now = 0;
3863         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3864         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3865         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3866     }
3867 }
3868 
3869 // parsing end emitting has been merged to reduce code size
3870 static void gap_inquiry_explode(uint8_t * packet){
3871     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
3872 
3873     uint8_t * eir_data;
3874     ad_context_t context;
3875     const uint8_t * name;
3876     uint8_t         name_len;
3877 
3878     int event_type = hci_event_packet_get_type(packet);
3879     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3880     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3881 
3882     // event[1] is set at the end
3883     int i;
3884     for (i=0; i<num_responses;i++){
3885         memset(event, 0, sizeof(event));
3886         event[0] = GAP_EVENT_INQUIRY_RESULT;
3887         uint8_t event_size = 18;    // if name is not set by EIR
3888 
3889         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3890         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3891         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3892         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3893 
3894         switch (event_type){
3895             case HCI_EVENT_INQUIRY_RESULT:
3896                 // 14,15,16,17 = 0, size 18
3897                 break;
3898             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3899                 event[14] = 1;
3900                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3901                 // 16,17 = 0, size 18
3902                 break;
3903             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3904                 event[14] = 1;
3905                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3906                 // for EIR packets, there is only one reponse in it
3907                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3908                 name = NULL;
3909                 // EIR data is 240 bytes in EIR event
3910                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3911                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3912                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3913                     const uint8_t * data = ad_iterator_get_data(&context);
3914                     // Prefer Complete Local Name over Shortend Local Name
3915                     switch (data_type){
3916                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3917                             if (name) continue;
3918                             /* explicit fall-through */
3919                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3920                             name = data;
3921                             name_len = data_size;
3922                             break;
3923                         default:
3924                             break;
3925                     }
3926                 }
3927                 if (name){
3928                     event[16] = 1;
3929                     // truncate name if needed
3930                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3931                     event[17] = len;
3932                     memcpy(&event[18], name, len);
3933                     event_size += len;
3934                 }
3935                 break;
3936         }
3937         event[1] = event_size - 2;
3938         hci_emit_event(event, event_size, 1);
3939     }
3940 }
3941 #endif
3942 
3943 void hci_emit_state(void){
3944     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3945     uint8_t event[3];
3946     event[0] = BTSTACK_EVENT_STATE;
3947     event[1] = sizeof(event) - 2;
3948     event[2] = hci_stack->state;
3949     hci_emit_event(event, sizeof(event), 1);
3950 }
3951 
3952 #ifdef ENABLE_CLASSIC
3953 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3954     uint8_t event[13];
3955     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3956     event[1] = sizeof(event) - 2;
3957     event[2] = status;
3958     little_endian_store_16(event, 3, con_handle);
3959     reverse_bd_addr(address, &event[5]);
3960     event[11] = 1; // ACL connection
3961     event[12] = 0; // encryption disabled
3962     hci_emit_event(event, sizeof(event), 1);
3963 }
3964 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3965     if (disable_l2cap_timeouts) return;
3966     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3967     uint8_t event[4];
3968     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3969     event[1] = sizeof(event) - 2;
3970     little_endian_store_16(event, 2, conn->con_handle);
3971     hci_emit_event(event, sizeof(event), 1);
3972 }
3973 #endif
3974 
3975 #ifdef ENABLE_BLE
3976 #ifdef ENABLE_LE_CENTRAL
3977 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3978     uint8_t event[21];
3979     event[0] = HCI_EVENT_LE_META;
3980     event[1] = sizeof(event) - 2;
3981     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3982     event[3] = status;
3983     little_endian_store_16(event, 4, con_handle);
3984     event[6] = 0; // TODO: role
3985     event[7] = address_type;
3986     reverse_bd_addr(address, &event[8]);
3987     little_endian_store_16(event, 14, 0); // interval
3988     little_endian_store_16(event, 16, 0); // latency
3989     little_endian_store_16(event, 18, 0); // supervision timeout
3990     event[20] = 0; // master clock accuracy
3991     hci_emit_event(event, sizeof(event), 1);
3992 }
3993 #endif
3994 #endif
3995 
3996 static void hci_emit_transport_packet_sent(void){
3997     // notify upper stack that it might be possible to send again
3998     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
3999     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
4000 }
4001 
4002 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
4003     uint8_t event[6];
4004     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
4005     event[1] = sizeof(event) - 2;
4006     event[2] = 0; // status = OK
4007     little_endian_store_16(event, 3, con_handle);
4008     event[5] = reason;
4009     hci_emit_event(event, sizeof(event), 1);
4010 }
4011 
4012 static void hci_emit_nr_connections_changed(void){
4013     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
4014     uint8_t event[3];
4015     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
4016     event[1] = sizeof(event) - 2;
4017     event[2] = nr_hci_connections();
4018     hci_emit_event(event, sizeof(event), 1);
4019 }
4020 
4021 static void hci_emit_hci_open_failed(void){
4022     log_info("BTSTACK_EVENT_POWERON_FAILED");
4023     uint8_t event[2];
4024     event[0] = BTSTACK_EVENT_POWERON_FAILED;
4025     event[1] = sizeof(event) - 2;
4026     hci_emit_event(event, sizeof(event), 1);
4027 }
4028 
4029 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
4030     log_info("hci_emit_dedicated_bonding_result %u ", status);
4031     uint8_t event[9];
4032     int pos = 0;
4033     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
4034     event[pos++] = sizeof(event) - 2;
4035     event[pos++] = status;
4036     reverse_bd_addr(address, &event[pos]);
4037     hci_emit_event(event, sizeof(event), 1);
4038 }
4039 
4040 
4041 #ifdef ENABLE_CLASSIC
4042 
4043 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
4044     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
4045     uint8_t event[5];
4046     int pos = 0;
4047     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
4048     event[pos++] = sizeof(event) - 2;
4049     little_endian_store_16(event, 2, con_handle);
4050     pos += 2;
4051     event[pos++] = level;
4052     hci_emit_event(event, sizeof(event), 1);
4053 }
4054 
4055 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
4056     if (!connection) return LEVEL_0;
4057     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
4058     return gap_security_level_for_link_key_type(connection->link_key_type);
4059 }
4060 
4061 static void hci_emit_discoverable_enabled(uint8_t enabled){
4062     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
4063     uint8_t event[3];
4064     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
4065     event[1] = sizeof(event) - 2;
4066     event[2] = enabled;
4067     hci_emit_event(event, sizeof(event), 1);
4068 }
4069 
4070 #ifdef ENABLE_CLASSIC
4071 // query if remote side supports eSCO
4072 int hci_remote_esco_supported(hci_con_handle_t con_handle){
4073     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4074     if (!connection) return 0;
4075     return connection->remote_supported_feature_eSCO;
4076 }
4077 
4078 // query if remote side supports SSP
4079 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
4080     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4081     if (!connection) return 0;
4082     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
4083 }
4084 
4085 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
4086     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
4087 }
4088 #endif
4089 
4090 // GAP API
4091 /**
4092  * @bbrief enable/disable bonding. default is enabled
4093  * @praram enabled
4094  */
4095 void gap_set_bondable_mode(int enable){
4096     hci_stack->bondable = enable ? 1 : 0;
4097 }
4098 /**
4099  * @brief Get bondable mode.
4100  * @return 1 if bondable
4101  */
4102 int gap_get_bondable_mode(void){
4103     return hci_stack->bondable;
4104 }
4105 
4106 /**
4107  * @brief map link keys to security levels
4108  */
4109 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
4110     switch (link_key_type){
4111         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4112             return LEVEL_4;
4113         case COMBINATION_KEY:
4114         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
4115             return LEVEL_3;
4116         default:
4117             return LEVEL_2;
4118     }
4119 }
4120 
4121 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
4122     log_info("gap_mitm_protection_required_for_security_level %u", level);
4123     return level > LEVEL_2;
4124 }
4125 
4126 /**
4127  * @brief get current security level
4128  */
4129 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
4130     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4131     if (!connection) return LEVEL_0;
4132     return gap_security_level_for_connection(connection);
4133 }
4134 
4135 /**
4136  * @brief request connection to device to
4137  * @result GAP_AUTHENTICATION_RESULT
4138  */
4139 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
4140     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4141     if (!connection){
4142         hci_emit_security_level(con_handle, LEVEL_0);
4143         return;
4144     }
4145     gap_security_level_t current_level = gap_security_level(con_handle);
4146     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
4147         requested_level, connection->requested_security_level, current_level);
4148 
4149     // assumption: earlier requested security higher than current level => security request is active
4150     if (current_level < connection->requested_security_level){
4151         if (connection->requested_security_level < requested_level){
4152             // increase requested level as new level is higher
4153 
4154             // TODO: handle re-authentication when done
4155 
4156             connection->requested_security_level = requested_level;
4157         }
4158         return;
4159     }
4160 
4161     // no request active, notify if security sufficient
4162     if (requested_level <= current_level){
4163         hci_emit_security_level(con_handle, current_level);
4164         return;
4165     }
4166 
4167     // start pairing to increase security level
4168     connection->requested_security_level = requested_level;
4169 
4170 #if 0
4171     // sending encryption request without a link key results in an error.
4172     // TODO: figure out how to use it properly
4173 
4174     // would enabling ecnryption suffice (>= LEVEL_2)?
4175     if (hci_stack->link_key_db){
4176         link_key_type_t link_key_type;
4177         link_key_t      link_key;
4178         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
4179             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
4180                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4181                 return;
4182             }
4183         }
4184     }
4185 #endif
4186 
4187     // start to authenticate connection
4188     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
4189     hci_run();
4190 }
4191 
4192 /**
4193  * @brief start dedicated bonding with device. disconnect after bonding
4194  * @param device
4195  * @param request MITM protection
4196  * @result GAP_DEDICATED_BONDING_COMPLETE
4197  */
4198 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
4199 
4200     // create connection state machine
4201     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
4202 
4203     if (!connection){
4204         return BTSTACK_MEMORY_ALLOC_FAILED;
4205     }
4206 
4207     // delete linkn key
4208     gap_drop_link_key_for_bd_addr(device);
4209 
4210     // configure LEVEL_2/3, dedicated bonding
4211     connection->state = SEND_CREATE_CONNECTION;
4212     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
4213     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
4214     connection->bonding_flags = BONDING_DEDICATED;
4215 
4216     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4217 
4218     // handle: connnection failure (connection complete != ok)
4219     // handle: authentication failure
4220     // handle: disconnect on done
4221 
4222     hci_run();
4223 
4224     return 0;
4225 }
4226 #endif
4227 
4228 void gap_set_local_name(const char * local_name){
4229     hci_stack->local_name = local_name;
4230 }
4231 
4232 
4233 #ifdef ENABLE_BLE
4234 
4235 #ifdef ENABLE_LE_CENTRAL
4236 void gap_start_scan(void){
4237     hci_stack->le_scanning_enabled = 1;
4238     hci_run();
4239 }
4240 
4241 void gap_stop_scan(void){
4242     hci_stack->le_scanning_enabled = 0;
4243     hci_run();
4244 }
4245 
4246 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4247     hci_stack->le_scan_type     = scan_type;
4248     hci_stack->le_scan_interval = scan_interval;
4249     hci_stack->le_scan_window   = scan_window;
4250     hci_run();
4251 }
4252 
4253 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4254     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4255     if (!conn){
4256         log_info("gap_connect: no connection exists yet, creating context");
4257         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4258         if (!conn){
4259             // notify client that alloc failed
4260             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4261             log_info("gap_connect: failed to alloc hci_connection_t");
4262             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4263         }
4264         conn->state = SEND_CREATE_CONNECTION;
4265         log_info("gap_connect: send create connection next");
4266         hci_run();
4267         return 0;
4268     }
4269 
4270     if (!hci_is_le_connection(conn) ||
4271         conn->state == SEND_CREATE_CONNECTION ||
4272         conn->state == SENT_CREATE_CONNECTION) {
4273         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4274         log_error("gap_connect: classic connection or connect is already being created");
4275         return GATT_CLIENT_IN_WRONG_STATE;
4276     }
4277 
4278     log_info("gap_connect: context exists with state %u", conn->state);
4279     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4280     hci_run();
4281     return 0;
4282 }
4283 
4284 // @assumption: only a single outgoing LE Connection exists
4285 static hci_connection_t * gap_get_outgoing_connection(void){
4286     btstack_linked_item_t *it;
4287     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4288         hci_connection_t * conn = (hci_connection_t *) it;
4289         if (!hci_is_le_connection(conn)) continue;
4290         switch (conn->state){
4291             case SEND_CREATE_CONNECTION:
4292             case SENT_CREATE_CONNECTION:
4293             case SENT_CANCEL_CONNECTION:
4294                 return conn;
4295             default:
4296                 break;
4297         };
4298     }
4299     return NULL;
4300 }
4301 
4302 uint8_t gap_connect_cancel(void){
4303     hci_connection_t * conn = gap_get_outgoing_connection();
4304     if (!conn) return 0;
4305     switch (conn->state){
4306         case SEND_CREATE_CONNECTION:
4307             // skip sending create connection and emit event instead
4308             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4309             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4310             btstack_memory_hci_connection_free( conn );
4311             break;
4312         case SENT_CREATE_CONNECTION:
4313             // request to send cancel connection
4314             conn->state = SEND_CANCEL_CONNECTION;
4315             hci_run();
4316             break;
4317         default:
4318             break;
4319     }
4320     return 0;
4321 }
4322 #endif
4323 
4324 #ifdef ENABLE_LE_CENTRAL
4325 /**
4326  * @brief Set connection parameters for outgoing connections
4327  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4328  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4329  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4330  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4331  * @param conn_latency, default: 4
4332  * @param supervision_timeout (unit: 10ms), default: 720 ms
4333  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4334  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4335  */
4336 
4337 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4338     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4339     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4340     hci_stack->le_connection_scan_interval = conn_scan_interval;
4341     hci_stack->le_connection_scan_window = conn_scan_window;
4342     hci_stack->le_connection_interval_min = conn_interval_min;
4343     hci_stack->le_connection_interval_max = conn_interval_max;
4344     hci_stack->le_connection_latency = conn_latency;
4345     hci_stack->le_supervision_timeout = supervision_timeout;
4346     hci_stack->le_minimum_ce_length = min_ce_length;
4347     hci_stack->le_maximum_ce_length = max_ce_length;
4348 }
4349 #endif
4350 
4351 /**
4352  * @brief Updates the connection parameters for a given LE connection
4353  * @param handle
4354  * @param conn_interval_min (unit: 1.25ms)
4355  * @param conn_interval_max (unit: 1.25ms)
4356  * @param conn_latency
4357  * @param supervision_timeout (unit: 10ms)
4358  * @returns 0 if ok
4359  */
4360 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4361     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4362     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4363     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4364     connection->le_conn_interval_min = conn_interval_min;
4365     connection->le_conn_interval_max = conn_interval_max;
4366     connection->le_conn_latency = conn_latency;
4367     connection->le_supervision_timeout = supervision_timeout;
4368     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4369     hci_run();
4370     return 0;
4371 }
4372 
4373 /**
4374  * @brief Request an update of the connection parameter for a given LE connection
4375  * @param handle
4376  * @param conn_interval_min (unit: 1.25ms)
4377  * @param conn_interval_max (unit: 1.25ms)
4378  * @param conn_latency
4379  * @param supervision_timeout (unit: 10ms)
4380  * @returns 0 if ok
4381  */
4382 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4383     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4384     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4385     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4386     connection->le_conn_interval_min = conn_interval_min;
4387     connection->le_conn_interval_max = conn_interval_max;
4388     connection->le_conn_latency = conn_latency;
4389     connection->le_supervision_timeout = supervision_timeout;
4390     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4391     hci_run();
4392     return 0;
4393 }
4394 
4395 #ifdef ENABLE_LE_PERIPHERAL
4396 
4397 static void gap_advertisments_changed(void){
4398     // disable advertisements before updating adv, scan data, or adv params
4399     if (hci_stack->le_advertisements_active){
4400         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4401     }
4402     hci_run();
4403 }
4404 
4405 /**
4406  * @brief Set Advertisement Data
4407  * @param advertising_data_length
4408  * @param advertising_data (max 31 octets)
4409  * @note data is not copied, pointer has to stay valid
4410  */
4411 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4412     hci_stack->le_advertisements_data_len = advertising_data_length;
4413     hci_stack->le_advertisements_data = advertising_data;
4414     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4415     gap_advertisments_changed();
4416 }
4417 
4418 /**
4419  * @brief Set Scan Response Data
4420  * @param advertising_data_length
4421  * @param advertising_data (max 31 octets)
4422  * @note data is not copied, pointer has to stay valid
4423  */
4424 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4425     hci_stack->le_scan_response_data_len = scan_response_data_length;
4426     hci_stack->le_scan_response_data = scan_response_data;
4427     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4428     gap_advertisments_changed();
4429 }
4430 
4431 /**
4432  * @brief Set Advertisement Parameters
4433  * @param adv_int_min
4434  * @param adv_int_max
4435  * @param adv_type
4436  * @param direct_address_type
4437  * @param direct_address
4438  * @param channel_map
4439  * @param filter_policy
4440  *
4441  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4442  */
4443  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4444     uint8_t direct_address_typ, bd_addr_t direct_address,
4445     uint8_t channel_map, uint8_t filter_policy) {
4446 
4447     hci_stack->le_advertisements_interval_min = adv_int_min;
4448     hci_stack->le_advertisements_interval_max = adv_int_max;
4449     hci_stack->le_advertisements_type = adv_type;
4450     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4451     hci_stack->le_advertisements_channel_map = channel_map;
4452     hci_stack->le_advertisements_filter_policy = filter_policy;
4453     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4454 
4455     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4456     gap_advertisments_changed();
4457  }
4458 
4459 /**
4460  * @brief Enable/Disable Advertisements
4461  * @param enabled
4462  */
4463 void gap_advertisements_enable(int enabled){
4464     hci_stack->le_advertisements_enabled = enabled;
4465     if (enabled && !hci_stack->le_advertisements_active){
4466         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4467     }
4468     if (!enabled && hci_stack->le_advertisements_active){
4469         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4470     }
4471     hci_run();
4472 }
4473 
4474 #endif
4475 
4476 void hci_le_set_own_address_type(uint8_t own_address_type){
4477     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4478     if (own_address_type == hci_stack->le_own_addr_type) return;
4479     hci_stack->le_own_addr_type = own_address_type;
4480 
4481 #ifdef ENABLE_LE_PERIPHERAL
4482     // update advertisement parameters, too
4483     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4484     gap_advertisments_changed();
4485 #endif
4486 #ifdef ENABLE_LE_CENTRAL
4487     // note: we don't update scan parameters or modify ongoing connection attempts
4488 #endif
4489 }
4490 
4491 #endif
4492 
4493 uint8_t gap_disconnect(hci_con_handle_t handle){
4494     hci_connection_t * conn = hci_connection_for_handle(handle);
4495     if (!conn){
4496         hci_emit_disconnection_complete(handle, 0);
4497         return 0;
4498     }
4499     // ignore if already disconnected
4500     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
4501         return 0;
4502     }
4503     conn->state = SEND_DISCONNECT;
4504     hci_run();
4505     return 0;
4506 }
4507 
4508 /**
4509  * @brief Get connection type
4510  * @param con_handle
4511  * @result connection_type
4512  */
4513 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4514     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4515     if (!conn) return GAP_CONNECTION_INVALID;
4516     switch (conn->address_type){
4517         case BD_ADDR_TYPE_LE_PUBLIC:
4518         case BD_ADDR_TYPE_LE_RANDOM:
4519             return GAP_CONNECTION_LE;
4520         case BD_ADDR_TYPE_SCO:
4521             return GAP_CONNECTION_SCO;
4522         case BD_ADDR_TYPE_CLASSIC:
4523             return GAP_CONNECTION_ACL;
4524         default:
4525             return GAP_CONNECTION_INVALID;
4526     }
4527 }
4528 
4529 #ifdef ENABLE_BLE
4530 
4531 #ifdef ENABLE_LE_CENTRAL
4532 /**
4533  * @brief Auto Connection Establishment - Start Connecting to device
4534  * @param address_typ
4535  * @param address
4536  * @returns 0 if ok
4537  */
4538 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4539     // check capacity
4540     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4541     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4542     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4543     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4544     entry->address_type = address_type;
4545     memcpy(entry->address, address, 6);
4546     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4547     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4548     hci_run();
4549     return 0;
4550 }
4551 
4552 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4553     btstack_linked_list_iterator_t it;
4554     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4555     while (btstack_linked_list_iterator_has_next(&it)){
4556         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4557         if (entry->address_type != address_type) continue;
4558         if (memcmp(entry->address, address, 6) != 0) continue;
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         // direclty remove entry from whitelist
4565         btstack_linked_list_iterator_remove(&it);
4566         btstack_memory_whitelist_entry_free(entry);
4567     }
4568 }
4569 
4570 /**
4571  * @brief Auto Connection Establishment - Stop Connecting to device
4572  * @param address_typ
4573  * @param address
4574  * @returns 0 if ok
4575  */
4576 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4577     hci_remove_from_whitelist(address_type, address);
4578     hci_run();
4579     return 0;
4580 }
4581 
4582 /**
4583  * @brief Auto Connection Establishment - Stop everything
4584  * @note  Convenience function to stop all active auto connection attempts
4585  */
4586 void gap_auto_connection_stop_all(void){
4587     btstack_linked_list_iterator_t it;
4588     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4589     while (btstack_linked_list_iterator_has_next(&it)){
4590         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4591         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4592             // remove from controller if already present
4593             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4594             continue;
4595         }
4596         // directly remove entry from whitelist
4597         btstack_linked_list_iterator_remove(&it);
4598         btstack_memory_whitelist_entry_free(entry);
4599     }
4600     hci_run();
4601 }
4602 #endif
4603 #endif
4604 
4605 #ifdef ENABLE_CLASSIC
4606 /**
4607  * @brief Set Extended Inquiry Response data
4608  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4609  * @note has to be done before stack starts up
4610  */
4611 void gap_set_extended_inquiry_response(const uint8_t * data){
4612     hci_stack->eir_data = data;
4613 }
4614 
4615 /**
4616  * @brief Start GAP Classic Inquiry
4617  * @param duration in 1.28s units
4618  * @return 0 if ok
4619  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4620  */
4621 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4622     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
4623     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4624     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4625         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4626     }
4627     hci_stack->inquiry_state = duration_in_1280ms_units;
4628     hci_run();
4629     return 0;
4630 }
4631 
4632 /**
4633  * @brief Stop GAP Classic Inquiry
4634  * @returns 0 if ok
4635  */
4636 int gap_inquiry_stop(void){
4637     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4638         // emit inquiry complete event, before it even started
4639         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4640         hci_emit_event(event, sizeof(event), 1);
4641         return 0;
4642     }
4643     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4644     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4645     hci_run();
4646     return 0;
4647 }
4648 
4649 
4650 /**
4651  * @brief Remote Name Request
4652  * @param addr
4653  * @param page_scan_repetition_mode
4654  * @param clock_offset only used when bit 15 is set
4655  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4656  */
4657 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4658     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4659     memcpy(hci_stack->remote_name_addr, addr, 6);
4660     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4661     hci_stack->remote_name_clock_offset = clock_offset;
4662     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4663     hci_run();
4664     return 0;
4665 }
4666 
4667 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4668     hci_stack->gap_pairing_state = state;
4669     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4670     hci_run();
4671     return 0;
4672 }
4673 
4674 /**
4675  * @brief Legacy Pairing Pin Code Response
4676  * @param addr
4677  * @param pin
4678  * @return 0 if ok
4679  */
4680 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4681     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4682     hci_stack->gap_pairing_input.gap_pairing_pin = pin;
4683     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4684 }
4685 
4686 /**
4687  * @brief Abort Legacy Pairing
4688  * @param addr
4689  * @param pin
4690  * @return 0 if ok
4691  */
4692 int gap_pin_code_negative(bd_addr_t addr){
4693     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4694     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4695 }
4696 
4697 /**
4698  * @brief SSP Passkey Response
4699  * @param addr
4700  * @param passkey
4701  * @return 0 if ok
4702  */
4703 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4704     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4705     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
4706     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4707 }
4708 
4709 /**
4710  * @brief Abort SSP Passkey Entry/Pairing
4711  * @param addr
4712  * @param pin
4713  * @return 0 if ok
4714  */
4715 int gap_ssp_passkey_negative(bd_addr_t addr){
4716     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4717     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4718 }
4719 
4720 /**
4721  * @brief Accept SSP Numeric Comparison
4722  * @param addr
4723  * @param passkey
4724  * @return 0 if ok
4725  */
4726 int gap_ssp_confirmation_response(bd_addr_t addr){
4727     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4728     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4729 }
4730 
4731 /**
4732  * @brief Abort SSP Numeric Comparison/Pairing
4733  * @param addr
4734  * @param pin
4735  * @return 0 if ok
4736  */
4737 int gap_ssp_confirmation_negative(bd_addr_t addr){
4738     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4739     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4740 }
4741 
4742 /**
4743  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4744  * @param inquiry_mode see bluetooth_defines.h
4745  */
4746 void hci_set_inquiry_mode(inquiry_mode_t mode){
4747     hci_stack->inquiry_mode = mode;
4748 }
4749 
4750 /**
4751  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4752  */
4753 void hci_set_sco_voice_setting(uint16_t voice_setting){
4754     hci_stack->sco_voice_setting = voice_setting;
4755 }
4756 
4757 /**
4758  * @brief Get SCO Voice Setting
4759  * @return current voice setting
4760  */
4761 uint16_t hci_get_sco_voice_setting(void){
4762     return hci_stack->sco_voice_setting;
4763 }
4764 
4765 /** @brief Get SCO packet length for current SCO Voice setting
4766  *  @note  Using SCO packets of the exact length is required for USB transfer
4767  *  @return Length of SCO packets in bytes (not audio frames)
4768  */
4769 int hci_get_sco_packet_length(void){
4770     int sco_packet_length = 0;
4771 
4772 #ifdef ENABLE_CLASSIC
4773 #ifdef ENABLE_SCO_OVER_HCI
4774     // see Core Spec for H2 USB Transfer.
4775 
4776     // CVSD requires twice as much bytes
4777     int multiplier = hci_stack->sco_voice_setting & 0x0020 ? 2 : 1;
4778 
4779     // 3 byte SCO header + 24 bytes per connection
4780     sco_packet_length = 3 + 24 * hci_number_sco_connections() * multiplier;
4781 #endif
4782 #endif
4783     return sco_packet_length;
4784 }
4785 
4786 /**
4787 * @brief Sets the master/slave policy
4788 * @param policy (0: attempt to become master, 1: let connecting device decide)
4789 */
4790 void hci_set_master_slave_policy(uint8_t policy){
4791     hci_stack->master_slave_policy = policy;
4792 }
4793 
4794 #endif
4795 
4796 HCI_STATE hci_get_state(void){
4797     return hci_stack->state;
4798 }
4799 
4800 
4801 /**
4802  * @brief Set callback for Bluetooth Hardware Error
4803  */
4804 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4805     hci_stack->hardware_error_callback = fn;
4806 }
4807 
4808 void hci_disconnect_all(void){
4809     btstack_linked_list_iterator_t it;
4810     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4811     while (btstack_linked_list_iterator_has_next(&it)){
4812         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4813         if (con->state == SENT_DISCONNECT) continue;
4814         con->state = SEND_DISCONNECT;
4815     }
4816     hci_run();
4817 }
4818 
4819 uint16_t hci_get_manufacturer(void){
4820     return hci_stack->manufacturer;
4821 }
4822 
4823 #ifdef ENABLE_BLE
4824 
4825 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4826     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4827     if (!hci_con) return NULL;
4828     return &hci_con->sm_connection;
4829 }
4830 
4831 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
4832 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
4833 
4834 int gap_encryption_key_size(hci_con_handle_t con_handle){
4835     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4836     if (!sm_conn) return 0;     // wrong connection
4837     if (!sm_conn->sm_connection_encrypted) return 0;
4838     return sm_conn->sm_actual_encryption_key_size;
4839 }
4840 
4841 int gap_authenticated(hci_con_handle_t con_handle){
4842     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4843     if (!sm_conn) return 0;     // wrong connection
4844     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
4845     return sm_conn->sm_connection_authenticated;
4846 }
4847 
4848 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
4849     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4850     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
4851     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
4852     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
4853     return sm_conn->sm_connection_authorization_state;
4854 }
4855 #endif
4856 
4857 #ifdef ENABLE_CLASSIC
4858 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){
4859     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4860     if (!conn) return GAP_CONNECTION_INVALID;
4861     conn->sniff_min_interval = sniff_min_interval;
4862     conn->sniff_max_interval = sniff_max_interval;
4863     conn->sniff_attempt = sniff_attempt;
4864     conn->sniff_timeout = sniff_timeout;
4865     hci_run();
4866     return 0;
4867 }
4868 
4869 /**
4870  * @brief Exit Sniff mode
4871  * @param con_handle
4872  @ @return 0 if ok
4873  */
4874 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
4875     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4876     if (!conn) return GAP_CONNECTION_INVALID;
4877     conn->sniff_min_interval = 0xffff;
4878     hci_run();
4879     return 0;
4880 }
4881 #endif
4882