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